Rust
Beginner
1 min read
Immutable and Mutable References
Example
fn main() {
// --- Immutable references ---
let s = String::from("hello");
let r1 = &s;
let r2 = &s; // multiple immutable refs are fine
println!("r1={r1} r2={r2} s={s}");
// --- Mutable reference ---
let mut data = String::from("foo");
append_bar(&mut data);
println!("data = {data}");
// --- Borrow checker prevents simultaneous mut + immut ---
let mut v = vec![1, 2, 3];
let first = &v[0]; // immutable borrow of v
println!("first = {first}");
// v.push(4); // compile error: cannot borrow `v` as mutable
// because it is also borrowed as immutable
// The immutable borrow ends after the last use of `first`
v.push(4); // now ok — first's lifetime has ended
println!("v = {:?}", v);
// --- Only one mutable reference at a time ---
let mut x = 5;
let m1 = &mut x;
*m1 += 10;
// let m2 = &mut x; // compile error: second mutable borrow
println!("x = {x}");
}
fn append_bar(s: &mut String) {
s.push_str("bar");
}