How does "?" know to create a box?

I always thought that "?" operator simply inserts a match evaluation against two arms of a function call but run into this example in the rustlings error handling error5.rs file that seems to suggest that it also does additional evaluation and seems to be able to create a box if necessary.

Is there docs that properly explain what "?" operator does besides simply adding dummy Result arms eval?

DOES NOT WORK

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let me = "blah";
    if me.len() > 2 {
        return Err("Invalid len"); //  <---- NO ?
    }
    Ok(())
}

WORKS

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let me = "blah";
    if me.len() > 2 {
        return Err("Invalid len")?;
    }
    Ok(())
}

? performs a From::from() conversion for the error case (of course, explicitly mentioned in the Book), and there's an impl From<&str> for Box<dyn Error>.

2 Likes

Note that the return is redundant here since ? already always returns on Err. Thus, you could rewrite it simply like this:

if me.len() > 2 {
    Err("Invalid len")?;
}

although I would prefer, for the sake of explicitness:

if me.len() > 2 {
    return Err("Invalid len".into());
}

(Rust Playground)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.