Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation about mutable statics to rust.md #7846

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions doc/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,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.
Expand Down