rust / beginner
Snippet
Variables and Mutability in Rust
In Rust, variables are immutable by default. This means once you assign a value to a variable, you cannot change it. This is a powerful feature that helps prevent bugs. If you need to change a variable's value, you must declare it with the 'mut' keyword. This explicit mutability makes code safer and easier to reason about.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
fn main() {let x = 5;let mut y = 10;println!("x = {}, y = {}", x, y);y = 15;// x = 6; // This would fail - x is immutableprintln!("y = {}", y);}
Breakdown
1
let x = 5;
Creates an immutable variable x with value 5
2
let mut y = 10;
Creates a mutable variable y with value 10
3
y = 15;
Successfully changes y to 15 because y is mutable