Activity 15 - Acting out ownership

To bring:

  • Tape/string
  • Blank paper

Act 1: Copy vs Move (6 students)

  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 (4 students)

  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 (8 students)

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

Finale: The Box Office (14 students!!)

fn main() {
    let ticket_number = 42;
    let venue = String::from("Stage");

    let guest_list = vec![
        String::from("Alice"),
        String::from("Bob")
    ];

    // Box in a Box!
    let vip_box = Box::new(Box::new(String::from("VIP")));

    let show = prepare_show(guest_list, vip_box);

    println!("Show at {} with ticket {}", venue, ticket_number);
    println!("Final show: {:?}", show);
}

fn prepare_show(mut guests: Vec<String>, special: Box<Box<String>>) -> Box<Vec<String>> {
    guests.push(String::from("Charlie"));
    guests.push(*special); // Unbox twice!
    Box::new(guests)
}