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

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.