可變的靜態變數

您可以放心讀取不可變的靜態變數:

static HELLO_WORLD: &str = "Hello, world!";

fn main() {
    println!("HELLO_WORLD: {HELLO_WORLD}");
}

不過,讀取並寫入可變的靜態變數並不安全,因為可能發生資料競爭:

static mut COUNTER: u32 = 0;

fn add_to_counter(inc: u32) {
    unsafe {
        COUNTER += inc;
    }
}

fn main() {
    add_to_counter(42);

    unsafe {
        println!("COUNTER: {COUNTER}");
    }
}
This slide should take about 5 minutes.
  • 這裡的程式採用單一執行緒,因此安全無虞。不過,Rust 編譯器較為保守,會設想最糟的情況。請嘗試移除 unsafe,看看編譯器如何解釋為什麼從多個執行緒變更 static,屬於未定義的行為。

  • 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.