Each heap value has one owner. Assigning a String moves ownership, so the original name can no longer be used.

Program

Play the program to watch s1 move into s2.

ownership_move.rs
Replay: real traced execution (multi-file project)
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;
    let len = s2.len();
    println!("{s2} {len}");
}
  1. s1 ← "hello", s2 ← "hello", len ← 5

    1fn main() {2    let s→ "hello"1 = String::from("hello");3    let s→ "hello"2 = s1;4    let le→ 5n = s2.len();5    println!("{s2} {len}");6}
    outputhello 5

Watch the Move

  1. s1 starts as the owner of "hello".
  2. let s2 = s1; moves the string to s2.
  3. s2.len() works because s2 is now the owner.
  4. Using s1 after the move would be the mistake to look for.
before move: s1 -> "hello"
after move:  s2 -> "hello"
             s1 is no longer usable
ownership A `String` owns heap memory through a single binding.
move `let s2 = s1` moves ownership; `s1` is no longer usable.
len `s2.len()` returns the byte length of the string.

Exercise: ownership_move.rs

Move a String into a new owner, trigger the old-name error once, then fix the print to use the current owner