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), ...

Get Rust Essentials - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.