rusterror-handlingoperators

What is the difference between adding the `?` operator and not adding it in this call?


In this code, what is the difference between adding the ? operator after the call to read_to_string() and not adding it? Why do both work = what happens if this call fails?

fn chaining() -> Result<String, std::io::Error> {
    let mut username = String::new();
    File::open("fake.txt")?.read_to_string(&mut username)?; // <- removing ? here also works
    Ok(username)
}

Solution

  • If you remove the ? operator, errors when reading the file will be silently ignored (although the compiler will warn you). If you keep it, errors will return from the function with Err. So you probably want to keep it.

    As for what happens to the String passed if you ignore the error, the documentation of read_to_string() refers to the documentation of read_to_end(), which says the following:

    If any other read error is encountered then this function immediately returns. Any bytes which have already been read will be appended to buf.