How to use Results

I'm struggling to work out how to use the Result types you get back from functions that return results.

If i use "if let" the variable seems to be inside the scope of the if statement so cant be accessed after it ends.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=52628fd9f2ba3b56f1d3ddacc95d9a61

Same with match

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=22402ba2b3f48a67d79bdb957c06c78b

A lot of examples I see just use .unwrap() but then say don't use this in a real world app as it could crash if you get an error. So what is the correct way to deal with this ?

1 Like

match and if can produce a value

let y = match x {
    Ok(y) => y,
    Err(e) => return Err(From::from(e)),
};

But the most common way is with ?

let y = x?;

The two examples are mostly equivalent, with ? being the slightly more powerful one as it can handle types other than Result.

4 Likes

I'm playing with tantivy and ended up doing this. cheers for the help.

 let index_res = tantivy::Index::open_in_dir(dir);
    let index = match index_res {
        Ok(index) => index,
        Err(_e) => {
            println!("Could not open index");
            return;
        }
    };

Just a nitpick but you can replace _e by _.

Since the name is not that long, I wouldn't even create index_res and just do:

let index = match tantivy::Index::open_in_dir(dir) {

but that's a personal choice.