How it works...

In the preceding recipe, we knew we had to exit the program using panic! in the case of an undesired input, but the main problem we are trying to solve in this recipe is the way by which we can handle None input. We use the Rust standard library to address this problem. More specifically, we use an enum called Option<T> from the std library, which is used when there is no input:

        enum Option<T> {
None,
Some(T),
}

It has two options, namely:

  • Some(T): This is an element of the type T that was sent
  • None: This refers to the case where there was no input

We handle these cases in two ways: the explicit way of handling in which we use match and the implicit way in which we use unwrap. The implicit way of handling returns the inner element of either enum or panic!.

In the explicit way of handling, we declared three variables, namely Desired_Book, Another_Book, and Empty_value in the main function. We assigned them with book names, which were Rust Cookbook, Another Book, and `None`, respectively. Post this, we called the functions in the following manner:

  • compare_stmt_match(Desired_Book): This satisfies the match statement condition Some("Rust CookBook") to print Rust CookBook was selected
  • compare_stmt_match(Another_Book): This satisfies the match statement condition Some(inner) to print "Rust CookBook not selected"
  • compare_stmt_match(Empty_val): This satisfies the match statement condition None to print No input provided

In implicit handling, we created Rand_Book and No_val with the values Some("Random Book") and None, respectively. We call another function that uses unwrap to handle Some(T) and None values. The compare_stmt_unwrap(Rand_Book) used unwrap to get inside_val, which successfully called the print statement; on the second function call compare_stmt_unwrap(No_val), we got thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', ../src/libcore/option.rs:323. This was because unwrap returns a panic when we have None as the inner value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.17.18