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
arginarg.unwrap()argis a reference.- but
unwrap()has signatureunwrap(self) -> T: it takes ownership! - Therefore
unwrapcannot take ownership (argdoesn'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.