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.

Same with match

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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.