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

    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.