capypad
0 day streak
rust / beginner
Snippet

Immutable and Mutable References

Rust uses references to allow access to data without taking ownership. Immutable references (&T) allow reading but not modifying. Mutable references (&mut T) allow both reading and modifying, but you can only have ONE mutable reference at a time - this prevents data races at compile time.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
fn main() {
let mut data = vec![1, 2, 3];
let immut_ref = &data;
println!("Immutable: {:?}", immut_ref);
let mut_ref = &mut data;
mut_ref.push(4);
println!("Mutable: {:?}", mut_ref);
}
Breakdown
1
let mut data = vec![1, 2, 3];
Creates a mutable vector with three elements
2
let immut_ref = &data;
Creates an immutable reference to data
3
let mut_ref = &mut data;
Creates a mutable reference - exclusive access
4
mut_ref.push(4);
Modifies the data through the mutable reference