Robin  van Leeuwen
Robin van Leeuwen

Reputation: 2703

Parse integer or provide default value with unwrap_or, but print error message when default value is used

I have written some code that parses a config file. If the config file holds a valid value for a field it sets in Config struct. If no valid integer value was found for a setting it sets a default value (e.g: 90).

let config = Config {
    interval: settings.get("interval").unwrap().parse().unwrap_or(90),
}

How can I make this to take a closure, so that it can print via error! and set default value?

Looking something like following:

let config = Config {
    interval: settings.get("interval").unwrap().parse().unwrap_or({
        error!("No interval found. Using default: 90");
        90
    });
}

But in this example, the error! is always executed, even if a valid value from interval was read from the config.

How can I make it so that unwrap_or only executes the code in optb when parse() has failed?

Upvotes: 3

Views: 1460

Answers (1)

Akiner Alkan
Akiner Alkan

Reputation: 6882

How can I make it so that unwrap_or only executes the code in optb when parse() has failed?

  • Arguments passed to unwrap_or are eagerly evaluated.

  • If you are passing the result of a function call, it is recommended to use unwrap_or_else which is lazily evaluated.

In your scenario it should be changed as following:

let config: Config = Config {
   interval: settings.get("interval").unwrap().parse().unwrap_or_else(|_| {
        error!("No interval found. Using default: 90");
        90
    }),
}

Playground


Also you should not use naked unwrap() in your production code. Error handling is better solution instead of using naked unwrap()

Here you can find detailed info about why you should not use unwrap()

Upvotes: 11

Related Questions