capypad
0 day streak
rust / beginner
Snippet

Variables and Immutability

In Rust, variables are immutable by default, meaning their value cannot change once bound. To allow a variable to be updated, you must explicitly use the 'mut' keyword.

snippet.rs
rust
1
2
3
4
5
6
7
fn main() {
let x = 5;
// x = 6; // This would cause a compile error
let mut y = 10;
y = 11; // This is allowed
println!("x: {x}, y: {y}");
}
Breakdown
1
let x = 5;
Declares an immutable variable x with the value 5.
2
let mut y = 10;
Declares a mutable variable y, allowing its value to be changed later.
3
y = 11;
Reassigns a new value to the mutable variable y.