Errors in main
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!
Press + to interact
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 yearsheight: u32, // in centimeters}impl Person {// Price to ride the roller coasterfn 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 laterenum CantRide {TooShort(String),TooYoung(String),}
There are three important ...