Static in Rust

In Rust, the term static refers to a type of global variable that has a fixed memory location and a lifetime that spans the entire duration of a program. Static variables are initialized at compile time and remain in a fixed location in memory, making them distinct from const variables, which are inlined wherever they are used. This entry explores the concept of static in Rust, including its characteristics, usage, and related concepts like lazy initialization.

Characteristics of Static Variables

  • Global Scope: Static variables are accessible from anywhere in the program, making them ideal for values that need to be shared across different parts of a program.
  • Fixed Memory Location: Once a static variable is initialized, it resides at a fixed memory location for the duration of the program.
  • Immutability by Default: By default, static variables are immutable. However, they can be made mutable using the static mut keyword, though this requires careful handling to avoid data races and undefined behavior.

Example of a Static Variable

Here is a simple example of a static variable in Rust:

static SEASONS: [&str; 4] = ["Spring", "Summer", "Fall", "Winter"];

In this example, SEASONS is a static array of string slices that represent the four seasons. This array is globally accessible and immutable.

Mutable Static Variables

While static variables are immutable by default, Rust allows for mutable static variables using the static mut keyword. However, modifying a static mut variable is unsafe and requires the use of the unsafe block to ensure that the programmer acknowledges the potential risks, such as data races.

Example of a Mutable Static Variable

static mut NUMBER: u32 = 0;

fn main() {
    let mut join_handle_vec = vec![];
    for _ in 0..10 {
        join_handle_vec.push(std::thread::spawn(|| {
            for _ in 0..10 {
                unsafe {
                    NUMBER += 1;
                }
            }
        }));
    }
    for handle in join_handle_vec {
        handle.join().unwrap();
    }
    unsafe {
        println!("{NUMBER}");
    }
}

In this example, NUMBER is a mutable static variable that is incremented by multiple threads. The use of unsafe blocks is necessary to modify NUMBER, highlighting the potential for data races.

Synchronization and Safe Concurrency

To safely modify static variables in a concurrent context, Rust provides synchronization primitives such as Mutex and RwLock. These allow for safe concurrent access and modification of static variables at runtime.

Lazy Initialization

For cases where a static variable requires runtime initialization, Rust provides crates like lazy_static and once_cell. These crates enable the creation of lazily evaluated statics, which are initialized only when they are first accessed.

Example of Lazy Initialization

use lazy_static::lazy_static;

lazy_static! {
    static ref POPULAR_BABY_NAMES_2020: Vec<String> = {
        vec![
            String::from("Olivia"),
            String::from("Liam"),
            String::from("Emma"),
            String::from("Noah"),
        ]
    };
}

In this example, the lazy_static! macro is used to define a global, immutable vector of popular baby names. If you need the data to be mutable, you could use Mutex<Vec<String>> or RwLock<Vec<String>>.

Thread-Local Static Variables

Rust provides the ability to declare thread-local static variables using the thread_local! macro. This is useful when you need a global variable that is local to each thread.

thread_local! {
    static POPULAR_BABY_NAMES_2021: Arc<Mutex<Option<Vec<String>>>> =
        Arc::new(Mutex::new(None));
}

In this listing, we use a reference counted pointer, Arc, and Mutex to safely share the inner data. The Vec<String> is wrapped in an Option because we cannot initialize a Vec or String at compile time. The pointer used to access the data is local to the current thread, but the data itself is global.

Limitations of Static Variables

Static variables cannot perform heap allocations. For example, the following code will not compile because Vec and String are heap-allocated:

static POPULAR_BABY_NAMES_2021: Vec<String> = vec![
    String::from("Olivia"),
    String::from("Liam"),
    String::from("Emma"),
    String::from("Noah"),
];

Attempting to compile this code will produce errors indicating that allocations are not allowed in statics and that non-const functions cannot be called in statics.

Conclusion

The static keyword in Rust provides a powerful mechanism for defining global variables with a fixed memory location and a lifetime that spans the entire program. While static variables offer benefits such as global accessibility and fixed memory location, they also come with limitations, such as immutability by default and restrictions on heap allocations. For more dynamic behavior, lazy initialization techniques using crates like lazy_static and once_cell can be employed. Understanding these concepts is crucial for effectively managing global state in Rust programs.

| Book Title | Usage of static | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-----------------|-----------------|-------------------------------|---------------|-----------------------|
| [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) | Discusses `static` variables as global variables with fixed memory locations, contrasting with `const`. Highlights immutability and the use of `static mut` for mutable statics. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-16/77) | Explains the need for `unsafe` blocks with `static mut` and synchronization with `Mutex` and `RwLock`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-16/47) | Connects `static` to concepts like global scope, immutability, and concurrency. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-2/63) | Provides examples of `static` and `static mut` variables, including a thread-safe counter. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-17/210) | Discusses practical use cases like lazy initialization with `lazy_static` and `once_cell`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-17/207) |
| [Idiomatic Rust](https://www.manning.com/books/idiomatic-rust) | Describes `static` variables as having a `'static` lifetime and being `Sync`. Discusses thread-local statics with `thread_local!`. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-4/184) | Covers limitations like no heap allocations and the need for `unsafe` with mutable statics. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-4/184) | Links `static` to thread safety and global state management with `lazy_static`. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-4/171) | Includes examples of thread-local statics and lazy initialization with `lazy_static`. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-4/171) | Emphasizes the use of `lazy_static` for managing global state and thread-local data. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-4/171) |
| [Write Powerful Rust Macros](https://www.manning.com/books/write-powerful-rust-macros) | Focuses on `lazy_static` for lazy initialization of static values, highlighting its runtime benefits. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/153) | Delves into the macro's internal mechanics, including type creation and initialization. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/153) | Explores the macro system and its role in extending Rust's capabilities. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/153) | Provides a detailed example of `lazy_static` and its internal workings. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/153) | Discusses the transition to `once_cell` and the performance and flexibility benefits of lazy initialization. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/153) |

FAQ (Frequently asked questions)

Do static variables in Rust perform heap allocations?

Is the drop() method called for static variables at shutdown in Rust?

What does 'static' mean in the context of the lazy_static macro?