1. 43
    Rustlings errors1: Propagating the reason something failed using Result, Err, and Ok
    1m 15s

Rustlings errors1: Propagating the reason something failed using Result, Err, and Ok

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

README for this exercise.

Chris Biscardi: [0:00] In errors1, we have a public function named generate_nametag_text() that takes a String and returns an optional type. An Option type allows us to return either a string or None using the Some or None keywords. This is great for signifying errors as we can return None if we can't get the value or Some value if we can, but it doesn't let us communicate the reason something failed.

[0:21] For that, we're going to use the Result type. In generate_nametag_text, we've change Option to Result. Option, in other languages, is sometimes called the Maybe type or Optional type, whereas Result is sometimes called Either. In this case, we have two constructors that we can use, which are OK and Err. We'll replace Some with OK. We'll replace None with Err.

[0:41] In our test, we can see the exact string that we want to pass in as Err. Note that if we try to write a string literal, the Rust compiler tells us that we expected a struct string and found a string slice instead. We can use String: :From to fix this. Note that on our first test, we're still expecting some as the result of generate_nametag_text. We should be expecting OK.

[1:00] Now, when our function gets called, we can verify that in the case of a valid value, we get OK wrapping the value. In the case of an error, we get Err wrapping the error value. This allows us to pattern match on OK or Err whenever we execute generate_nametag_text.