Ownership & Borrow Checker
Last updated
fn main() {
let toy = String::from("Toy car"); // `toy` owns the string
let new_owner = toy; // `toy` is moved to `new_owner`
// println!("{}", toy); // Error! `toy` no longer owns the value
println!("{}", new_owner); // This works since `new_owner` is the current owner
}fn main() {
let mut toy = String::from("Toy car");
// `toy` is borrowed mutably by `decorate`
decorate(&mut toy);
println!("{}", toy); // Prints: "Toy car with stickers"
}
fn decorate(toy: &mut String) {
toy.push_str(" with stickers"); // Modify the borrowed `toy`
}fn main() {
let toy = String::from("Toy car");
let look1 = &toy; // Immutable borrow
let look2 = &toy; // Another immutable borrow
println!("Look 1: {}", look1); // Prints: "Look 1: Toy car"
println!("Look 2: {}", look2); // Prints: "Look 2: Toy car"
// `toy.push_str(" new")`; // Error! Cannot modify `toy` while it is immutably borrowed
}fn main() {
let toy = String::from("Toy car"); // `toy` owns the string
{
let _borrowed_toy = &toy; // `_borrowed_toy` borrows `toy`
println!("Inside scope: {}", _borrowed_toy); // Works within this inner scope
} // `_borrowed_toy` goes out of scope here
println!("Outside scope: {}", toy); // Still accessible since `toy` is still in scope
} // `toy` goes out of scope and is automatically cleaned up