auto merge of #7846 : alexcrichton/rust/static-mut-dox, r=pnkfelix

It's probably a good idea to at least *mention* them somewhere.
This commit is contained in:
bors 2013-07-18 13:49:36 -07:00
commit 78f8b407e3

View file

@ -1122,6 +1122,41 @@ static bits_n_strings: BitsNStrings<'static> = BitsNStrings {
};
~~~~
#### Mutable statics
If a static item is declared with the ```mut``` keyword, then it is allowed to
be modified by the program. One of Rust's goals is to make concurrency bugs hard
to run into, and this is obviously a very large source of race conditions or
other bugs. For this reason, an ```unsafe``` block is required when either
reading or writing a mutable static variable. Care should be taken to ensure
that modifications to a mutable static are safe with respect to other tasks
running in the same process.
Mutable statics are still very useful, however. They can be used with C
libraries and can also be bound from C libraries (in an ```extern``` block).
~~~
# fn atomic_add(_: &mut uint, _: uint) -> uint { 2 }
static mut LEVELS: uint = 0;
// This violates the idea of no shared state, and this doesn't internally
// protect against races, so this function is `unsafe`
unsafe fn bump_levels_unsafe1() -> uint {
let ret = LEVELS;
LEVELS += 1;
return ret;
}
// Assuming that we have an atomic_add function which returns the old value,
// this function is "safe" but the meaning of the return value may not be what
// callers expect, so it's still marked as `unsafe`
unsafe fn bump_levels_unsafe2() -> uint {
return atomic_add(&mut LEVELS, 1);
}
~~~
### Traits
A _trait_ describes a set of method types.