Activity 22: The Box Office, and Debugging Ownership
Name(s):
Part 1: The Box Office
Cast: 11 people.
fn main() { 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 {}", venue); 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) }
Part 2: three programs that won't compile
For each one:
- Read the compiler message.
- Describe briefly what went wrong, in terms of owners
- Try to come up with two different fixes. Which would you use, and why?
Error 1
fn main() { let data = vec![1, 2, 3]; process_data(data); println!("{:?}", data); } fn process_data(vec: Vec<i32>) { println!("Processing: {:?}", vec); }
Compiler says: borrow of moved value: data
What went wrong:
Fix 1:
Fix 2:
Which would you use, and why?
Error 2
fn main() { let message = String::from("Hello"); let a = message; let b = message; println!("{} {}", a, b); }
Compiler says: use of moved value: message
What went wrong:
Fix 1:
Fix 2:
Which would you use, and why?
Error 3
fn main() { let names = vec![String::from("Alice"), String::from("Bob")]; let first = names[0]; println!("{}", first); }
Compiler says: cannot move out of index of Vec<String>
What went wrong:
Fix 1:
Fix 2:
Which would you use, and why?
Bonus. This program compiles fine:
fn main() { let numbers = vec![10, 20, 30]; let first = numbers[0]; println!("{}", first); }
Same shape, no error. What's different?
Solutions
Error 1
data moved into process_data and was dropped at its closing brace.
Fix 1: have process_data return the vector, and rebind let data = process_data(data);.
Fix 2: process_data(data.clone()).
Error 2
message moved into a, so there's nothing left to move into b.
Fix 1: let a = message.clone(); and move the original into b
Fix 2: Clone both, or use &
Error 3
Moving the String out would leave a hole in the vector.
Fix 1: names[0].clone().
Fix 2: &names[0]
Bonus: same shape, no error
What's different?
i32 is Copy and String isn't.