Tutorial by Examples

The const keyword declares a global constant binding. const DEADBEEF: u64 = 0xDEADBEEF; fn main() { println("{:X}", DEADBEEF); } This outputs DEADBEEF
The static keyword declares a global static binding, which may be mutable. static HELLO_WORLD: &'static str = "Hello, world!"; fn main() { println("{}", HELLO_WORLD); } This outputs Hello, world!
Use the lazy_static crate to create global immutable variables which are initialized at runtime. We use HashMap as a demonstration. In Cargo.toml: [dependencies] lazy_static = "0.1.*" In main.rs: #[macro_use] extern crate lazy_static; lazy_static! { static ref HASHMAP: Hash...
A thread-local object gets initialized on its first use in a thread. And as the name suggests, each thread will get a fresh copy independent of other threads. use std::cell::RefCell; use std::thread; thread_local! { static FOO: RefCell<f32> = RefCell::new(1.0); } // When this mac...
Mutable global items (called static mut, highlighting the inherent contradiction involved in their use) are unsafe because it is difficult for the compiler to ensure they are used appropriately. However, the introduction of mutually exclusive locks around data allows memory-safe mutable globals. Th...

Page 1 of 1