Using the return operator in the match expression. Early return of an error

Hello everyone. I can't understand why the early return of an error in the expression match is needed. How does it differ from the usual return error, and in what cases should it be used?
I'm reading chapter 9 which talks about panic!, one of the paragraphs talks about early return of the error, but I didn't find an explanation for why this is needed...

Can you copy-paste the relevant code snippet here?

1 Like

Sure. The line Err (e) => return Err (e) and the line Err (e) => Err (e). What is the difference?

#![allow(unused)]
fn main() {
use std::fs::File;
use std::io;
use std::io::Read;

fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");

    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();

    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}
}

Please use 3 backticks on each the top and the bottom of the code snippet. It's not really all that readable as it is now.

Sorry my bad. Corrected it

The return keyword causes a function to return early. Otherwise, the function will continue executing until the end of its body.

When you write return Err(e), the function returns early and the rest of its body does not execute.

If you change this to Err(e), then the match expression would have the value Err(e). The value of the match expression gets assigned to the variable f. Then the function continues executing on its next line.

In other words, without the return, this would be equivalent to:

let temp;
match f {
    Ok(file) => temp = file,
    Err(e) => temp = Err(e),
}
let mut f = temp;

And this causes a type error because Err(e) and file have two different types, so you can't assign them to the same variable.

4 Likes

An explicit return does what it says on the tin: it returns, immediately and unconditionally, from the enclosing function. An explicit return is needed whenever you want to return early from a function, without executing the rest of the function body.

In contrast, the last match doesn't contain explicit returns, because that match expression is the very last expression in the function body, and the last expression of the function body is automatically returned, even without an explicit return statement.

This is true in general as well: Rust is an expression language, and most language constructs, such as match and if, are expressions. Block-like language elements (including the aforementioned two kinds of expressions, as well as bare blocks and function bodies) are also expressions and yield the value of their last contained expression automatically.

2 Likes

Thanks a lot! Now I understand how it works!

Thanks a lot! :slight_smile: