Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ownership and strings

  • take ownership
fn main() {
    let name = String::from("Foo");
    println!("{name}");
    take_ownership(name);
    //println!("{name}"); // take_ownership moved the owner
}

fn take_ownership(name: String) {
    println!("in function: {name}");
}
Foo
in function: Foo
  • borrow
fn main() {
    let name = String::from("Foo");
    println!("{name}");
    borrow(&name);
    println!("{name}");
}

fn borrow(name: &str) {
    println!("in function: {name}");
}
  • give ownership
fn main() {
    let name = give_ownership();
    println!("{name}");
}

fn give_ownership() -> String {
    String::from("Foo")
}