Implicit or explicit return in non-closures. What is more idiomatic?

Hi, coming from Node I try to learn idiomatic Rust code. Opposite to JavaScript Rust offers explicit or implicit returns, so I wonder what would be more idiomatic here?

use std::error::Error;
use std::fs::File;
use std::io::Read;

fn read_file(path: &str) -> String {
    let mut file = match File::open(path) {
        Err(err) => panic!("Couldn't open: {}", err.description()),
        Ok(file) => file,

    let mut data = String::new();
    match file.read_to_string(&mut data) {
        Err(err) => panic!("Couldn't read: {}", err.description()),
        Ok(_) => (),
    // return data;  // THIS???
    data             // OR THIS???

fn main() {
    let hello = read_file("hello.txt");
    let world = read_file("world.txt");

    println!("Content is: {}", hello);
    println!("Content is: {}", world);
1 Like

I don't think that there are extremely strong feelings about this in the community, but I think that the variant without return is preferable. I myself avoid returns if possible.

On the unrelated note, I think this error handling can be implemented more compactly as let mut file = File::open(path).unwrap_or_else(|_err| panic!("Coundn't open: {}", path)). Note that the err.description() string will not include the file name, which is most relevant here.


Yeah, I should have said that this example is part of a tutorial series where I explore different kinds of error handling patterns. This is the starting point of all examples :slight_smile:

The official style is "return is only for early returns."



Should the compiler warn for return in non-early returns just like it warns for not using snake_case?

There may be some exceptions, but in general the style things the compiler warns about seriously impact other users' ability to reason about code, because the case of an ident helps readers parse what sort of term it is (that is: variable, constant, type, etc). Style choices like whether or not to use the return keyword aren't usually enforced by rustc.

Those kinds of things are checked by the clippy lint suite, which has a lint for unnecessary returns.