Skip to content

Constants vs Static Variables in Rust: Key Differences with Examples

Constants and Static Variable

Constants (const)

• Purpose: Compile-time fixed values that never change.
• Memory Efficiency:

• Constants are inlined at compile time, meaning the value is directly embedded wherever it’s used.
• No separate memory allocation at runtime, making them highly efficient.

• Use Case: Best for fixed, unchanging values like mathematical constants, configuration settings, or limits.

Example:

const PI: f64 = 3.14159; // Inlined wherever used

Static Variables (static)

• Purpose: Global variables that persist for the entire program’s lifetime.
• Memory Efficiency:

• Allocated at a fixed memory address in the program’s global memory.
• Access requires reading from that memory location, which is slightly less efficient than inlined constants.
• Mutable static variables may require synchronization in multi-threaded contexts, adding overhead.

• Use Case: Suitable for globally shared data or persistent, large structures.

Example:

const PI: f64 = 3.14159; // Inlined wherever used

Key Differences

FeatureConstants (const)Static Variables (static)
MemoryInlined, no runtime memory allocationFixed memory address at runtime
PerformanceFaster (no runtime access cost)Slightly slower (global memory access)
MutabilityAlways immutableCan be mutable (with unsafe)
Use CaseLightweight, frequently used valuesPersistent, globally shared data

Which to Choose?

• Use const:

• For immutable, lightweight, and frequently used values.
• When maximum memory efficiency and performance are required.

Use static:

• For persistent, globally shared data or large structures.
• When you need a single memory location for data across your program.

Leave a Reply

Your email address will not be published. Required fields are marked *