Static and Constant Variables

Global state is managed with static and constant variables.

const

You can declare compile-time constants:

  1. const DIGEST_SIZE: usize = 3;
  2. const ZERO: Option<u8> = Some(42);
  3. fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
  4. let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];
  5. for (idx, &b) in text.as_bytes().iter().enumerate() {
  6. digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b);
  7. }
  8. digest
  9. }
  10. fn main() {
  11. let digest = compute_digest("Hello");
  12. println!("Digest: {digest:?}");
  13. }

According the the Rust RFC Book these are inlined upon use.

static

You can also declare static variables:

  1. static BANNER: &str = "Welcome to RustOS 3.14";
  2. fn main() {
  3. println!("{BANNER}");
  4. }

As noted in the Rust RFC Book, these are not inlined upon use and have an actual associated memory location. This is useful for unsafe and embedded code, and the variable lives through the entirety of the program execution.

We will look at mutating static data in the chapter on Unsafe Rust.

  • Mention that const behaves semantically similar to C++’s constexpr.
  • static, on the other hand, is much more similar to a const or mutable global variable in C++.
  • It isn’t super common that one would need a runtime evaluated constant, but it is helpful and safer than using a static.