YouTip LogoYouTip

Rust Ownership and Borrowing

Ownership

let s1 = String::from("hello");
let s2 = s1;  // s1 is moved, no longer valid
// println!("{}", s1); // Error!

let s3 = s2.clone();  // explicit copy

Borrowing

fn print_len(s: &String) {
    println!("{}", s.len());
}
let s = String::from("hello");
print_len(&s);  // borrow
println!("{}", s);  // still valid

Summary

  • Each value has one owner
  • & borrows without taking ownership
← MySQL Tutorial - Getting StartRust Tutorial - Getting Starte β†’