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.
const MAX_POINTS: u32 = 100_000; fn main() { println!("Max points: {}", MAX_POINTS); }
| Step | Action | Value/Result | Notes |
|---|---|---|---|
| 1 | Declare constant MAX_POINTS | MAX_POINTS = 100_000 | Constant set once, cannot change |
| 2 | Enter main function | Start main | Program begins execution |
| 3 | Print MAX_POINTS | Output: Max points: 100000 | Uses constant value |
| 4 | End program | Program ends | No changes to MAX_POINTS |
| Variable | Start | After 1 | After 2 | Final |
|---|---|---|---|---|
| MAX_POINTS | undefined | 100000 | 100000 | 100000 |
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
MAX_POINTS with value 100 in Rust?const, require a type annotation, and use an equals sign to assign a value.const MAX_POINTS: i32 = 100;. const MAX_POINTS = 100; misses the type, var MAX_POINTS: i32 = 100; uses invalid keyword var, let MAX_POINTS: i32 = 100; uses let for variables.const + type + value = D [OK]const PI: f64 = 3.14;
fn main() {
println!("Value of PI is {}", PI);
}PI is declared with type f64 and value 3.14. It is used inside println! macro.{} with the value of PI, which is 3.14. No errors occur.const MAX: i32 = 10;
fn main() {
MAX = 20;
println!("{}", MAX);
}MAX = 20; tries to change the constant, which causes a compile-time error.u32 and value 7, which is correct syntax.let which is not a constant. const DAYS_IN_WEEK = 7;
fn total_days(weeks: u32) -> u32 {
weeks * DAYS_IN_WEEK
} misses the type annotation. static DAYS_IN_WEEK: u32 = 7;
fn total_days(weeks: u32) -> u32 {
weeks + DAYS_IN_WEEK
} uses static and adds weeks and days, which is incorrect logic.Pass the test and this pattern moves unknown