O'Reilly logo

Rust Essentials - Second Edition 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 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), ...

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