let and Mutability
Bindings and mut.
Binding Values with let
In Rust you create a variable with the let keyword. This binds a name to a value.
By default every binding is immutable — once you give it a value, you cannot change it.
fn main() {
let x = 5;
println!("The value of x is: {}", x);
}Immutable by Default
Rust makes variables immutable on purpose. This prevents accidental changes and makes code easier to reason about.
Trying to reassign an immutable binding causes a compile error, not a runtime crash.
let x = 5;thenx = 6;will not compile.
fn main() {
let x = 5;
// x = 6; // this would cause a compile error
println!("x stays {}", x);
}All lessons in this course
- let and Mutability
- Scalar Types
- Compound Types
- Shadowing