Help understanding the borrow checker

⚓ Rust    📅 2026-01-19    👤 surdeus    👁️ 8      

surdeus

Hello all

Sorry if this question is not for this category, please let me know if that's the case.
Need some help understanding the borrow checker while I learn rust.
Why this works without any issues?

fn main() {
let mut s = String::from("Hello");

let r1 = &mut s;
change_string(r1);
let r2 = &mut s;
change_string(r2);

println!("{}", s);

}

fn change_string(some_string: &mut String) {
some_string.push_str(" gordy!!!");
}

And this one, by the contrary, does not compile?

let r1 = &mut s;
let r2 = &mut s;    
change_string(r1);
change_string(r2);

println!("{}", s);

}

Is r1 "consumed" somehow or "ignored" in the first case?

Many thanks in advance.
Regards

4 posts - 4 participants

Read full topic

🏷️ Rust_feed