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!.

  • maegul (he/they)OPM
    link
    fedilink
    English
    arrow-up
    1
    ·
    6 months ago

    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()
    }
    
    1. arg does not live long enough
    2. cannot move out of arg in arg.unwrap()
    3. cannot call arg.is_none() without dereferencing arg
    4. cannot return s.clone() which does not live long enough
    Answer

    2

    • cannot move arg in arg.unwrap()
      • arg is a reference.
      • but unwrap() has signature unwrap(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.