O'Reilly logo

Rust Essentials by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Matching patterns

But how will we test whether input_num from the previous section, which is of the Result type, contains a value or not? When the value is an Ok(T) function, the unwrap() function can extract T like this:

println!("Unwrap found {}", input_num.unwrap());

Which prints: Unwrap found 42. However, when the result is an Err value, this lets the program crash with a panic, which is thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value'. This is bad!

To solve this, no complex if – else constructs will be enough; we need Rust's magical match here, which has a lot more possibilities than the switch in other languages, and is used frequently when handling errors:

match input_num {
   Ok(num) => println!("{}", num),
 Err(ex) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required