fn takes_ownership(s: String) {
println!("owned: {s}");
} // s is dropped here
fn borrows(s: &String) {
println!("borrowed: {s}");
} // s is NOT dropped — caller still owns it
fn borrows_mut(s: &mut String) {
s.push_str(" — modified");
}
fn main() {
let mut s = String::from("hello");
borrows(&s); // OK — many immutable borrows allowed
borrows(&s); // OK
borrows_mut(&mut s); // mutable borrow — only one at a time
println!("{s}"); // "hello — modified"
takes_ownership(s); // moves s
// println!("{s}"); // ❌ compile error: s was moved
}
Create a free account and build your private vault. Share publicly whenever you want.