Using match to choose one of several patterns

You might have noticed in our previous example that we did not handle the case where the function returned an error value. In part, that's because handling that situation with if let is a little bit awkward. We could do this:

if let Ok(x) = might_fail(39) {
println!("Odd succeeded, name is {}", x.name);
}
else if let Err(x) = might_fail(39) {
println!("Odd failed, message is '{}'", x);
}

But that runs the function twice when it doesn't have to, so it's inefficient. We could fix that by doing this:

let result = might_fail(39);
if let Ok(x) = result {
println!("Odd succeeded, name is {}", x.name);
}
else if let Err(x) = result {
println!("Odd failed, message is '{}'", x);
}

That's better, but variables are for storing information and we don't really need the result value anymore once we've checked for the success or failure of the function, so there's no reason to keep storing it.

We can use a match expression for situations like this, for the best results:

match might_fail(39) {
Ok(x) => { println!("Odd succeeded, name is {}", x.name) }
Err(x) => { println!("Odd failed, message is '{}'", x) }
}

A match expression matches a single value (in this case, the result of calling might_fail(39)) against multiple patterns, until it finds a pattern that successfully matches the value, then runs the code block associated with that particular pattern. The patterns are matched from top to bottom so, normally, we put the most specific patterns first and the most generic patterns last.

Individual patterns in a match expression don't have to cover all of the possibilities for the value, but all of them together need to. If Result had three possibilities instead of two (

OkErr, and a hypothetical Dunno, for example), then our previous match expression would not compile, because we hadn't told it what to do in the case of Dunno.

That's a difference from a series of if let and el
se if let, which are free to ignore as many possibilities as they want. If we use match, the compiler will tell us if we've missed a possibility, so we should always use match when we intend to handle all of the options. On the other hand, if let is for cherry-picking one or a few special cases.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.107.254