Variables, Mutability, and Constants
Learn how Rust stores values and why immutability is the default.
Learning objectives
- Declare variables using let
- Use mut when a variable needs to change
- Create constants for fixed values
Immutable by Default
In Rust, variables are immutable by default. This means once a value is assigned, you cannot change it unless you explicitly mark the variable as mutable. This design helps reduce accidental changes in your program.
Using mut
When a variable must change, use the mut keyword. This tells Rust and other readers of your code that the value is intended to be updated.
Constants
Constants are declared with const. They must have a type annotation and are useful for values that should never change, such as limits, rates, and configuration values.
Example code
fn main() {
let name = "Rust";
let mut score = 10;
score = score + 5;
const MAX_SCORE: i32 = 100;
println!("Language: {}", name);
println!("Score: {} of {}", score, MAX_SCORE);
}
Practice task: Create a mutable variable called total, add two values to it, and print the final result.