1. 46
    Rustlings errorsn: Using Box to dynamically return one of multiple error types at runtime
    1m 1s

Rustlings errorsn: Using Box to dynamically return one of multiple error types at runtime

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 errorsn, we have quite a bit of code, almost 115 lines of it. We have a number of use statements, a read_and_validate() function which is the one that we care about, a test_with_str() function, and a number of tests.

[0:12] The problem right now is that we need to specify a type and the result for the error type, but that our function can return multiple different kinds of errors, including one from parse() here up to two different kinds of errors from PositiveNonzerInteger: :new and one from read_line.

[0:27] We can use the question mark operator to return the errors when they happen, but we still need a type here. Because there are multiple different error types, we'll use the Box <dyn error: :Error>. This is a run-time way of determining which errors being returned from this read_and_validate() function.

[0:44] Note that because we're returning a result type, we'll also have to return OK {answer}, and our tests pass. If we know explicitly what errors we can return here with more boilerplate, we can specify them so that they're statically analyzable for the rest of our program, but in this case, the dynamic error works fine.

egghead
egghead
~ an hour 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