January 2019
Beginner to intermediate
554 pages
13h 31m
English
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.rsstatic 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 ...
Read now
Unlock full access