After Chs 5 and 6 (see the reading club post here), we get a capstone quiz that covers ownership along with struts
and enums
.
So, lets do the quiz together! If you’ve done it already, revisiting might still be very instructive! I certainly thought these questions were useful “revision”.
I’ll post a comment for each question with the answer, along with my own personal notes (and quotes from The Book if helpful), behind spoiler tags.
Feel free to try to answer in a comment before checking (if you dare). But the main point is to understand the point the question is making, so share any confusions/difficulties too, and of course any corrections of my comments/notes!.
Q2
/// Makes a string to separate lines of text, /// returning a default if the provided string is blank fn make_separator(user_str: &str) -> &str { if user_str == "" { let default = "=".repeat(10); &default } else { user_str } }
Normally if you try to compile this function, the compiler returns the following error:
error[E0515]: cannot return reference to local variable `default` --> test.rs:6:9 | 6 | &default | ^^^^^^^^ returns a reference to data owned by the current function
Assume that the compiler did NOT reject this function. Which (if any) of the following programs would (1) pass the compiler, and (2) possibly cause undefined behavior if executed? Check each program that satisfies both criteria, OR check “None of these programs” if none are satisfying.
// 1 let s = make_separator(""); // 2 let s = make_separator(""); println!("{s}"); // 3 println!("{}", make_separator("Hello world!"));
Answer
&default
, which results in a dangling pointer being returned. Then, it’s any program that uses the returned reference (so printing will do the trick)