flâneur

Constants and statics - Rust for C-Programmers

rust-for-c-programmers.com · 290 words · saved by 1 readers

Constants represent values that are known at compile time. They must be annotated with a type and are typically defined in the global scope, though they can also be defined within functions. Constants are effectively inlined wherever they are used and do not have a fixed memory address. The naming convention is SCREAMING_SNAKE_CASE. Static variables represent values that have a fixed memory location ('static lifetime) throughout the program’s execution. They are initialized once, usually when the program starts. Like constants, they must have an explicit type annotation. The naming convention is also SCREAMING_SNAKE_CASE. Rust strongly discourages mutable static variables (static mut) because modifying global state without synchronization can easily lead to data races in concurrent code. Accessing or modifying static mut variables requires unsafe blocks.

Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help 2.6 Constants and Static Variables Rust offers two ways to define values with fixed meaning or location: 2.6.1 Constants (const) Constants represent values that are known at compile time. They must be annotated with a type and are typically defined in the global scope, though they can also be defined within functions. Constants are effectively inlined wherever they are used and do not have a fixed memory address. The naming convention…

saved by

related reading