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/ match input_num { Ok(num) => println!("{}", num), ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.