Errors in main
Explore how to implement error handling in Rust's main function by using the Result type and custom error variants. Understand how the ? operator facilitates early exit on errors and how to return appropriate results, enhancing your ability to write robust Rust programs.
We'll cover the following...
Quite a while ago, we mentioned that main can return a few things besides unit (). Now that we’ve learned about Result, it’s about time we demonstrated that. Behold, our error-inducing main function!
There are three important things to point out here:
-
The result type of
mainisResult<(), CantRide>. This says, if everything goes OK, I’ll produce a unit value. But if there’s a problem, I’ll produce aCantRide. Returning the unit value for theOkvariant is pretty common in Rust error handling code. -
Inside the
println!macro call, we’ve stuck a?right after theprice_peoplefunction call. -
That last line,
Ok(()), is really interesting. Ourmainfunction needs to return a value of typeResult<(), CantRide>, and so we need to make sure we provide it. You’ll end up seeing a lot of code in Rust that includes lines like that as the last line in the function.
The program above will produce the output Error: TooYoung("Charlie"). If you comment out the Charlie line, then you’ll get Error: TooShort("David"). And finally, if you comment out David too, you’ll get the output, The price is 16. Hurrah!