Matching patterns
But how will we test whether input_num
from the previous section, which is of type Result
, contains a value or not? When the value is an Ok(T)
, the function unwrap()
can extract the value T
, like this:
println!("Unwrap found {}", input_num.unwrap());
This prints the following output:
Unwrap found 42
But when the result is an Err
value, this lets the program crash with a panic:
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value'.
This is bad! To solve this, no complex if - else
constructs will do; we need Rust's magical match
here, which has a lot more possibilities than the case or switch in other languages:
// from Chapter 4/code/pattern_match.rs match input_num { Ok(num) => println!("{}", num), Err(ex) => println!("Please input an integer number! {}", ex) };
The match
tests the value of an expression against all possible values. Only the code (which could be a block) after the arrow =>
of the first matching branch is executed....