ruipacheco
ruipacheco

Reputation: 16422

How to fail in struct creation?

I'm creating a struct that should get its values from an ini file. I have a load method that loads the file and returns an Option<Settings>.

What is the best way to fail and abort the struct creation? Should I return None or call fail!? Returning None seems to be the idiomatic way to handle this but fail! allows me to display a message.

How can I fail and send a message to my user, more or less what I'd do with exceptions in C++/Java?

Upvotes: 0

Views: 106

Answers (1)

Paige Ruten
Paige Ruten

Reputation: 176665

You want to use the Result type from the standard library. It lets you return either an Ok with the value or an Err with an error message (or whatever type of value you want). Then the caller of load() can handle printing out the error message to the user.

Here's an example:

enum DivError {
    DivisionByZero
}

fn divide(a: int, b: int) -> Result<int, DivError> {
    if b == 0 {
        Err(DivisionByZero)
    } else {
        Ok(a / b)
    }
}

fn main() {
    let answer = divide(1, 0);

    match answer {
        Ok(result) => println!("The answer is {}.", result),
        Err(DivisionByZero) => println!("Oops! You divided by zero.")
    }
}

Upvotes: 2

Related Questions