2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
minutes: 5
|
|
|
|
---
|
|
|
|
|
2022-12-21 16:36:30 +01:00
|
|
|
# Mutable Static Variables
|
|
|
|
|
|
|
|
It is safe to read an immutable static variable:
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
static HELLO_WORLD: &str = "Hello, world!";
|
|
|
|
|
|
|
|
fn main() {
|
2023-02-09 07:48:18 +01:00
|
|
|
println!("HELLO_WORLD: {HELLO_WORLD}");
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
However, since data races can occur, it is unsafe to read and write mutable
|
|
|
|
static variables:
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
static mut COUNTER: u32 = 0;
|
|
|
|
|
|
|
|
fn add_to_counter(inc: u32) {
|
|
|
|
unsafe { COUNTER += inc; } // Potential data race!
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
add_to_counter(42);
|
|
|
|
|
2023-02-09 07:48:18 +01:00
|
|
|
unsafe { println!("COUNTER: {COUNTER}"); } // Potential data race!
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
```
|
2023-01-17 16:21:02 +00:00
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-10-09 15:15:26 +02:00
|
|
|
- The program here is safe because it is single-threaded. However, the Rust compiler is conservative
|
|
|
|
and will assume the worst. Try removing the `unsafe` and 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_std` code, such as implementing a heap allocator or working with some C APIs.
|
2023-01-17 16:21:02 +00:00
|
|
|
|
|
|
|
</details>
|