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

Activity 21: Acting out ownership

What everything is

  • A person is a variable. Their name is taped on and never moves
  • Red is a value. A number is a blue sheet in the variable's own hands: the stack
  • A heap value is a blue sheet at the side of the room, held by someone with no name tag. The heap has addresses, not names
  • A leash is a pointer. The variable holds the handle end. The clip end is on the heap sheet
  • Whoever holds the leash owns the value. When the owner is done, they let go, and the sheet gets thrown out

Act 1: Copy vs Move

Cast: x, y, s1, s2, one heap holder, the allocator.

  fn main() {
      let x = 5;
      let y = x;
      let s1 = String::from("hello");
      let s2 = s1;
      println!("{} {}", x, y);
      // println!("{} {}", s1, s2);
  }

Act 2: Function calls and returning ownership

Cast: data, numbers, a second data, one heap holder, the allocator. Tape the rectangle for process.

  fn main() {
      let data = vec![1, 2, 3];
      let data = process(data);
      println!("{:?}", data); // Works!
  }

  fn process(mut numbers: Vec<i32>) -> Vec<i32> {
      numbers.push(4);
      numbers
  }

Act 3: Attack of the Clones

Cast: s1, s2, s3, s4, two heap holders, the allocator.

  fn main() {
      let s1 = String::from("hello");
      let s2 = s1.clone();
      println!("{} {}", s1, s2); 
      let s3 = s1;
      let s4 = s2;
      println!("{} {}", s3, s4); 
  }