Search⌘ K
AI Features

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!

Rust 1.40.0
fn main() -> Result<(), CantRide> {
let family = [
Person { name: "Alice".to_owned(), age: 30, height: 160 },
Person { name: "Bob".to_owned(), age: 35, height: 170 },
Person { name: "Charlie".to_owned(), age: 8, height: 100 },
Person { name: "David".to_owned(), age: 12, height: 75 },
];
println!("The price is {}", price_people(&family)?);
Ok(())
}
struct Person {
name: String,
age: u32, // in years
height: u32, // in centimeters
}
impl Person {
// Price to ride the roller coaster
fn price(&self) -> Result<u32, CantRide> {
if self.age < 10 {
return Err(CantRide::TooYoung(self.name.clone()));
}
if self.height < 80 {
return Err(CantRide::TooShort(self.name.clone()));
}
Ok(if self.age < 18 {
5
} else if self.age < 66 {
8
} else {
7
})
}
}
fn price_people(people: &[Person]) -> Result<u32, CantRide> {
let mut price = 0;
for person in people {
price += person.price()?;
}
Ok(price)
}
#[derive(Debug)] // for the output later
enum CantRide {
TooShort(String),
TooYoung(String),
}

There are three important things to point out here:

  1. The result type of main is Result<(), CantRide>. This says, if everything goes OK, I’ll produce a unit value. But if there’s a problem, I’ll produce a CantRide. Returning the unit value for the Ok variant is pretty common in Rust error handling code.

  2. Inside the println! macro call, we’ve stuck a ? right after the price_people function call.

  3. That last line, Ok(()), is really interesting. Our main function needs to return a value of type Result<(), 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!