liveBook · Manning

Static field

As explained in Learn Rust in a Month of Lunches

A Rust program item representing a value stored at a fixed memory location for the entire program lifetime.

A static field is a Rust value stored at a fixed memory location for the entire program lifetime. Declare it with an explicit type, usually outside main, and write its name in uppercase. Unlike const, a static may not be created at compile time. section 2.3

Static fields provide several practical guarantees:

  • Access them from anywhere in the program, including functions that receive no argument. section 2.3
  • Keep them alive for the whole program and avoid ordinary ownership or dropping concerns. section 2.3 section 2.11
  • Use a fixed memory location when that distinction matters; use const for values that are compile-time and unchangeable. section 2.3

A program-wide static value

static SEASONS: [&str; 4] = ["Spring", "Summer", "Fall", "Winter"]; fn print_months() { println!("Number of months in the year: {NUMBER_OF_MONTHS}"); } const NUMBER_OF_MONTHS: u32 = 12; fn main() { print_months(); } The function can use the global value without receiving it as an argument. Values such as these are convenient, but they must be known in a form Rust can create without runtime heap allocation. section 2.3

A mutable static, written static mut, can change directly only inside unsafe code. Concurrent access can create aliasing violations or data races, producing undefined behavior. A ten-thread counter may appear correct, while a larger run loses increments; synchronized types such as Arc<Mutex> provide controlled access instead. section 16.4.2

const NUMBER_OF_MONTHS: u32 = 12;
static SEASONS: [&str; 4] = ["Spring", "Summer", "Fall", "Winter"];

Use this minimal listing to compare the explicit declarations and uppercase naming convention for const and static values. section 2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains declaration syntax, fixed storage, lifetime, compile-time limits, and unsafe mutable access with a concurrency failure example.
Examples
Uses global month and season values, then contrasts a small successful counter with a large multithreaded static mut counter.
What it assumes
Assumes basic Rust variables and functions while building toward ownership, memory, threads, and unsafe-code reasoning.
What you can do after
Apply static declarations for global values and diagnose why mutable static access requires unsafe code.
How it connects
Connects static fields to const, global variables, ownership, heap allocation, unsafe Rust, threads, data races, and Arc<Mutex>.

Also explained in

Compare how 7 books explain static field →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.