memtrace

Memory regions

  • Stack Memory
  • Heap Memory
  • Static Memory

Ownership model

  • Ownership & Moves
  • Borrowing & References
Open the Playground
VisualizersStatic Memory

Static Memory

Why statics exist before main starts, outlive every frame, and are read without copying

What's happening · 01 / 07

Before anything runs

Statics are baked into the compiled program, so they exist before main starts. Each &str static is a pointer and a length to text in read-only memory

Code

1static GREETING_GLOBAL: &str = "Hello, universe!";// ← already in the binary
2
3fn main() {
4 println!("{}", GREETING);
5 println!("{}", GREETING_GLOBAL);
6
7 static GREETING: &str = "Hello, world!";
8}

Static Memory

Why statics exist before main starts, outlive every frame, and are read without copying

HIGH ADDRESSESStackframes and localsHeapBox, String, Vec dataStatic datastatics, string literalsCodecompiled machine codeLOW ADDRESSES
Where this lives in a running program
PROGRAM LIFETIMEGREETING&'static strmain()run()run()STARTEND
The idea in one picture

Step by step

Key takeaways

  • Statics exist before main and last until the process exits
  • A static inside a function is still a static; only its name is scoped
  • A &'static str is a pointer and a length into read-only memory
  • Passing a &str copies the pointer, never the text

Resources

  • The Rust Reference: Static itemsThe exact rules for statics, including static mut
  • Rust by Example: 'staticThe two meanings of 'static, with examples
  • std::println!What println! really expands to

Research notes

  • A const is inlined wherever it is used and has no fixed address, while a static has exactly one address for the whole program
  • Reading or writing a static mut needs unsafe, because any thread could be changing it at the same time
  • As a trait bound, T: 'static means the type holds no borrows shorter than 'static, not that the value lives forever
stdoutempty

$cargorun// waiting for the first println!

Auto-play steps