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@lemmy.mlOPM
    link
    fedilink
    English
    arrow-up
    1
    ·
    7 days ago

    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?

    1. user_str does not live long enough
    2. function make_separator cannot return two different references
    3. function make_separator cannot return a reference of type &str
    4. cannot return reference to local variable default
    Answer

    Cannot return reference to a local variable

    • &default isn’t allowed as default is local to the function.
      • What’s the fix? Copy? Just return "=".repeat(10) directly?
      • How about just return an owned String (requires converting user_str to a String with to_string())

    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.