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 3 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.

egghead
egghead
~ 15 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today