0
0
Rustprogramming~10 mins

Constants in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Constants
Declare constant with 'const'
Assign fixed value
Use constant in code
Value cannot change
Program runs
Constants are declared once with 'const', assigned a fixed value, and used without changing throughout the program.
Execution Sample
Rust
const MAX_POINTS: u32 = 100_000;

fn main() {
    println!("Max points: {}", MAX_POINTS);
}
This code declares a constant MAX_POINTS and prints its value.
Execution Table
StepActionValue/ResultNotes
1Declare constant MAX_POINTSMAX_POINTS = 100_000Constant set once, cannot change
2Enter main functionStart mainProgram begins execution
3Print MAX_POINTSOutput: Max points: 100000Uses constant value
4End programProgram endsNo changes to MAX_POINTS
💡 Program ends after printing constant value; constants cannot be changed.
Variable Tracker
VariableStartAfter 1After 2Final
MAX_POINTSundefined100000100000100000
Key Moments - 2 Insights
Why can't we change the value of MAX_POINTS after declaring it?
Because MAX_POINTS is declared with 'const', it is immutable and fixed at compile time, as shown in execution_table step 1 where it is set once and never changes.
Can constants be declared inside functions?
Yes, constants can be declared inside functions, but they are then scoped to that function. They remain immutable and fixed at compile time.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of MAX_POINTS at step 3?
Aundefined
B0
C100000
DCannot be determined
💡 Hint
Refer to execution_table row 3 where MAX_POINTS is printed with value 100000.
At which step does the program print the constant value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check execution_table row 3 for the print action.
If we try to assign a new value to MAX_POINTS after step 1, what would happen?
ACompile-time error
BThe program runs normally
CRuntime error
DValue changes successfully
💡 Hint
Constants declared with 'const' cannot be changed; see key_moments about immutability.
Concept Snapshot
Constants in Rust:
- Declared with 'const' keyword
- Must have explicit type
- Assigned fixed value at compile time
- Immutable: value cannot change
- Accessible globally or in module scope
Full Transcript
This visual execution shows how constants work in Rust. First, a constant MAX_POINTS is declared with the 'const' keyword and assigned the value 100000. This value is fixed and cannot be changed later. When the program runs, it enters the main function and prints the constant's value. The constant remains unchanged throughout the program. Constants have explicit types. Trying to change a constant causes a compile-time error.