rust / beginner
Snippet
Mutable Variables with let mut
In Rust, variables are immutable by default for safety. Using 'let mut' makes a variable mutable, allowing you to change its value after assignment. This is different from references - 'mut' applies to the variable itself, not how you access it.
snippet.rs
1
2
3
4
5
6
7
8
9
10
fn main() {let mut counter = 0;counter += 1;println!("Counter value: {}", counter);let name = String::from("Alice");let mut nickname = name;nickname.push_str("~");println!("Nickname: {}", nickname);}
Breakdown
1
let mut counter = 0;
Declares a mutable integer variable 'counter' with initial value 0
2
counter += 1;
Modifies the variable's value since it is mutable
3
let mut nickname = name;
'mut' allows reassignment of the binding itself