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!.
Q1
/// 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 } }
When compiling, what’s the best description of the compiler error?
- user_str does not live long enough
- function make_separator cannot return two different references
- function make_separator cannot return a reference of type &str
- cannot return reference to local variable default
Answer
Cannot return reference to a local variable
&default
isn’t allowed asdefault
is local to the function.- What’s the fix? Copy? Just return
"=".repeat(10)
directly? - How about just return an owned
String
(requires convertinguser_str
to aString
withto_string()
)
- What’s the fix? Copy? Just return
Context: Because default lives on the stack within make_separator, it will be deallocated once a call to make_separator ends. This leaves &default pointing to deallocated memory. Rust therefore complains that you cannot return a reference to a local variable.
Q6: Fixing
Of the following fixes (highlighted in yellow), which fix best satisfies these three criteria:
- The fixed function passes the Rust compiler,
- The fixed function preserves the intention of the original code, and
- The fixed function does not introduce unnecessary inefficiencies
/// Gets the string out of an option if it exists, /// returning a default otherwise fn get_or_default(arg: &Option<String>) -> String { if arg.is_none() { return String::new(); } let s = arg.unwrap(); s.clone() }
1:
fn get_or_default(arg: &Option<&str>) -> String { if arg.is_none() { return String::new(); } let s = arg.unwrap(); s.to_string() }
2:
fn get_or_default(arg: &mut Option<String>) -> String { if arg.is_none() { return String::new(); } let s = arg.as_mut().unwrap(); s.clone() }
3:
fn get_or_default(arg: Option<String>) -> String { if arg.is_none() { return String::new(); } let s = arg.unwrap(); s.clone() }
4:
fn get_or_default(arg: &Option<String>) -> String { match arg { None => String::new(), Some(s) => s.clone() } }
Answer
4
- Really about best-practices here
4
is a better, more idiomatic version of3
, especially because it requires ownership ofarg
which is restrictive and may not even be available- But I think
3
does fix the problem
- But I think
1
doesn’t fix the problem2
… I’m not sure about … but I don’t think having a mutables
helps with the problem either (?)
Context: The combination of is_none and unwrap here is a Rust anti-pattern, since a match combines the two functionalities and automatically deals with pushing the reference &Option into the interior to produce &String. Therefore the match solution is the most idiomatic, and passes the compiler without changing the intended type signature of the function.
The solution of changing &Option to Option is not desirable because it requires the caller to provide ownership of their option, which is a far more restrictive API.
Q4: Method and Ownership
- What best describes the compiler error
/// Gets the string out of an option if it exists, /// returning a default otherwise fn get_or_default(arg: &Option<String>) -> String { if arg.is_none() { return String::new(); } let s = arg.unwrap(); s.clone() }
- arg does not live long enough
- cannot move out of arg in arg.unwrap()
- cannot call arg.is_none() without dereferencing arg
- cannot return s.clone() which does not live long enough
Answer
2
- cannot move
arg
inarg.unwrap()
arg
is a reference.- but
unwrap()
has signatureunwrap(self) -> T
: it takes ownership! - Therefore
unwrap
cannot take ownership (arg
doesn’t have ownership to move/give).
Context: The function Option::unwrap expects self, meaning it expects ownership of arg. However arg is an immutable reference to an option, so it cannot provide ownership of the option. Therefore the compiler complains that we cannot move out of arg via unwrap.
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.
- None of these programs
// 1 let s = make_separator(""); // 2 let s = make_separator(""); println!("{s}"); // 3 println!("{}", make_separator("Hello world!"));
Answer
- Slightly dodgy question, as the undefined behaviour first requires an empty string to be passed in to trigger the return of
&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)
Context: First, the caller must pass an empty string to trigger the problematic if-condition. This returns a dangling pointer. Second, the caller must use the result of make_separator, e.g. via println.
Q3: How fix
Of the following fixes (highlighted in yellow), which fix best satisfies these three criteria:
- The fixed function passes the Rust compiler,
- The fixed function preserves the intention of the original code, and
- The fixed function does not introduce unnecessary inefficiencies
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
- Return owned
default
- Convert
user_str
to aString
to keep a consistent return type - Change return type to
String
2
is too restrictive in requiringuse_str
to be aString
1
doesn’t solve the problem
fn make_separator(user_str: &str) -> String { if user_str == "" { let default = "=".repeat(10); default } else { user_str.to_string() } }
Context: There is no valid way to return a pointer to a stack-allocated variable. The simple solution is therefore to change the return type to String and copy the input user_str into an owned string. However, requiring user_str to be a String would reduce the flexibility of the API, e.g. a caller could not call make_separator on a substring of a bigger string. It would also require callers to heap-allocate strings, e.g. they could not use a string literal like make_separator(“Rust”).
The most idiomatic solution to this problem uses a construct you haven’t seen yet: Cow - Clone-on-write. The clone-on-write smart pointer would enable this function to return either an owned string or a string reference without a type error.
- Interesting!!
deleted by creator
Q5
- Which programs would pass the compiler (presuming this function, from above, passes too) and possibly cause undefined behaviour?
/// Gets the string out of an option if it exists, /// returning a default otherwise fn get_or_default(arg: &Option<String>) -> String { if arg.is_none() { return String::new(); } let s = arg.unwrap(); s.clone() }
Options:
- None of these programs
// 1 let opt = Some(String::from("Rust")); let s = get_or_default(&opt); println!("{}", s); // 2 let opt = Some(String::from("Rust")); get_or_default(&opt); // 3 let opt = Some(String::from("Rust")); get_or_default(&opt); println!("{:?}", opt);
Answer
-
All programs (1, 2 and 3).
-
Once
arg.unwrap()
occurs,s
takes ownership of the underlyingString
. -
Once
s
“dies”, theString
is deallocated. -
But,
opt
, from before the call toget_or_default
also owns the sameString
, and so once it “dies” and its memory is deallocated, adouble-free
will occur. -
This actually threw me at first
-
My answer was program
3
, as I figured thatopt
had to be used in some way for “undefined behaviour” to occur, as only then, did I figure, would the inappropriate memory be used resulting in an incorrect result -
This is kinda wrong, though, because deallocation occurs once
opt
’s lifetime ends, which will cause a double-free.println
prolongs the lifetime while in program2
the lifetime ofopt
clearly ends, I suppose, causing the double-free.- I personally think this is completely ambiguous, and unless I’m missing something, these undefined behaviour questions easily suffer from these problems.