To use or not to use braces

Is there a difference between using and not using ?

Err(e) =>panic!("Problem creating the file: {:?}", e)   ,
other_error => {
                panic!("Problem opening the file {:?}", other_error)
            }

Full snippet is below:

use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("test.txt");

    match f {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating the file: {:?}", e),
            },
            other_error => {
                panic!("Problem opening the file {:?}", other_error)
            }
        },
    };
}

If you have more than one statement in the match arm you need the braces.

1 Like

Thank you for response. Is there a difference when there is only one statement ? Why in the code different styles ?

Personal preference / cosmetic.

1 Like

More generally, a block is an expression that can support multiple statements. You can use them all sorts of places, this is just a common example where blocks and non-blocks are used. Closure bodies is another.

2 Likes

Note that panic! is a little special because it diverges, so it has the never type ! which can coerce to any other type. But if your match arm needs to return nothing, i.e. the unit type (), then you could use a semicolon and braces to suppress other expression types. For example, { vec.pop(); } will drop the Option -- or you can literally write drop(vec.pop()).

4 Likes