1. 45
    Rustlings errors3: Using the `?` operator in the main function
    1m 19s

Rustlings errors3: Using the `?` operator in the main function

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 errors3, we have a main() function that includes the usage of the question mark that we used in errors2. Note that we also have a usage of the question mark in our total_cost() function. The Rust compiler tells us that "the 'question mark' operator can only be used in a function that returns 'Result' or 'Option' -- or another type that influenced the 'Try' trait."

[0:17] Luckily, in Rust 2018, we can specify that our main() function returns a Result type. The error is going to be a ParseIntError because that's what total_cost can return, which means that this question mark will return the ParseIntError from total_cost and this question mark will return the ParseIntError that we returned from total_cost, will return it to main.

[0:36] We know that the error that main can return is a ParseIntError. We still need a value here. You'll note that we don't return anything else from the main() function if we succeed. This value will be unit.

[0:46] Note that if you use a fat arrow instead of a skinny arrow, the Rust compiler will tell you that it expected a semicolon or a brace. Similarly, in the Result type -- that is the Return type for the main() -- if you use parentheses instead of the greater than and less than signs, you'll get a Rust compiler error about "only 'Fn' traits may use parentheses, use angle brackets instead."

[1:07] Finally, once we've declared that main can return a result type, we need to make sure that our main() function actually Returns a result type. We can do this by implicitly returning OK with the unit value at the end of our function.

egghead
egghead
~ 4 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