Statics

Statics are proper global values, as in they have a fixed memory location and exist as a single instance in the whole program. These can also be made mutable. However, as global variables are a breeding ground for the nastiest bugs out there, there are some safety mechanisms in place. Both reading and writing to statics has to be done inside an unsafe {} block. Here's how we crate and use statics:

// statics.rs

static mut BAZ: u32 = 4;
static FOO: u8 = 9;

fn main() {
unsafe {
println!("baz is {}", BAZ);
BAZ = 42;
println!("baz is now {}", BAZ);
println!("foo is {}", FOO);
}
}

In the code, we've declared two statics BAZ and FOO. We use the static keyword to create them along with specifying the type explicitly. If we want them to be mutable, we add the mut keyword after static. Statics aren't inlined like constants. When we read or write the static values, we need to use an unsafe block. Statics are generally combined with synchronization primitives for any kind of thread-safe use. They are also used to implement global locks and when integrating with C libraries.

Generally, if you don't need to rely on singleton property of statics and its predefined memory location and just want a concrete value, you should prefer using consts. They allow the compiler to make better optimizations and are more straightforward to use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset