capypad
0 day streak
rust / beginner
Snippet

Variables and Mutability in Rust

In Rust, variables are immutable by default, which encourages writing safer code. To make a variable mutable, you must explicitly use the `mut` keyword. This design prevents accidental modifications and makes code behavior easier to reason about.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
fn main() {
let immutable = 42;
println!("Immutable: {}", immutable);
 
let mut mutable_var = 10;
println!("Before mutation: {}", mutable_var);
 
mutable_var = 15;
println!("After mutation: {}", mutable_var);
 
}
Breakdown
1
let immutable = 42;
Creates an immutable variable. Its value cannot be changed after initialization.
2
let mut mutable_var = 10;
Creates a mutable variable with `mut`. The value can be reassigned later.
3
mutable_var = 15;
Successfully reassigns the mutable variable to a new value.