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!.
Q3: How fix
Of the following fixes (highlighted in yellow), which fix best satisfies these three criteria:
1:
fn make_separator(user_str: &str) -> &str { if user_str == "" { let default = "=".repeat(10); &default } else { &user_str } }
2:
fn make_separator(user_str: String) -> String { if user_str == "" { let default = "=".repeat(10); default } else { user_str } }
3:
fn make_separator(user_str: &str) -> String { if user_str == "" { let default = "=".repeat(10); default } else { user_str.to_string() } }
Answer
3
default
user_str
to aString
to keep a consistent return typeString
2
is too restrictive in requiringuse_str
to be aString
1
doesn’t solve the problemfn make_separator(user_str: &str) -> String { if user_str == "" { let default = "=".repeat(10); default } else { user_str.to_string() } }