Mutable Static Variables
It is safe to read an immutable static variable:
1. ```
static HELLO_WORLD: &str = "Hello, world!";
```
3. ```
fn main() {
```
4. ```
println!("HELLO_WORLD: {HELLO_WORLD}");
```
5. ```
}
```
However, since data races can occur, it is unsafe to read and write mutable static variables:
1. ```
static mut COUNTER: u32 = 0;
```
3. ```
fn add_to_counter(inc: u32) {
```
4. ```
// SAFETY: There are no other threads which could be accessing `COUNTER`.
```
5. ```
unsafe {
```
6. ```
COUNTER += inc;
```
7. ```
}
```
8. ```
}
```
10. ```
fn main() {
```
11. ```
add_to_counter(42);
```
13. ```
// SAFETY: There are no other threads which could be accessing `COUNTER`.
```
14. ```
unsafe {
```
15. ```
println!("COUNTER: {COUNTER}");
```
16. ```
}
```
17. ```
}
```
This slide should take about 5 minutes.
- The program here is safe because it is single-threaded. However, the Rust compiler is conservative and will assume the worst. Try removing the
unsafeand see how the compiler explains that it is undefined behavior to mutate a static from multiple threads. - Using a mutable static is generally a bad idea, but there are some cases where it might make sense in low-level
no_stdcode, such as implementing a heap allocator or working with some C APIs.
