116

I have something like this (the real function is Ini::Section::get from rust-ini):

impl Foo {
    pub fn get<K>(&'a mut self, key: &K) -> Option<&'a str>
    where
        K: Hash + Eq,
    {
        // ...
    }
}

I have to call it several times:

fn new() -> Result<Boo, String> {
    let item1 = match section.get("item1") {
        None => return Result::Err("no item1".to_string()),
        Some(v) => v,
    };
    let item2 = match section.get("item2") {
        None => return Result::Err("no item2".to_string()),
        Some(v) => v,
    };
}

To remove code bloat, I can write a macro like this:

macro_rules! try_ini_get {
    ($e:expr) => {
        match $e {
            Some(s) => Ok(s),
            None => Err("no ini item".to_string()),
        }
    }
}

Is there any way to remove the code duplication without this macro implementation?

0

2 Answers 2

173

The ok_or and ok_or_else methods convert Options to Results, and the ? operator automates the boilerplate associated with early Err returns.

You could do something like:

fn new() -> Result<Boo, String> {
    let item1 = section.get("item1").ok_or("no item1")?;
    let item2 = section.get("item2").ok_or("no item2")?;
    // whatever processing...
    Ok(final_result)
}
2
  • 12
    The difference between ok_or and ok_or_else: "Arguments passed to ok_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use ok_or_else, which is lazily evaluated."
    – MakotoE
    Jul 23, 2020 at 18:18
  • @MakotoE: Sure. I only used ok_or() because the passed argument is a constant.
    – isekaijin
    Jul 23, 2020 at 21:15
40

If you're using the crate anyhow you can import the anyhow::Context trait which adds the .context method on Options to turn them into anyhow::Results:

use anyhow::{Result, Context};

fn new() -> Result<Boo> {
    let item1 = section.get("item1").context("no item1")?;
    let item2 = section.get("item2").context("no item2")?;
    // whatever processing...
    Ok(final_result)
}
4
  • 1
    This solved casting Option to Result if Option is None for me. I can now have None as a propagated error condition in my function that returns Result<(), Box<dyn Error>> thanks
    – Bots Fab
    Feb 17, 2022 at 2:03
  • I haven't used Rust in a while. If this answer reflects current best practices, then it should be marked as accepted instead of mine.
    – isekaijin
    Mar 2, 2022 at 3:12
  • 2
    A simple dependency-free solution will always be the best practice IMHO, the accepted answer is good.
    – joseLuís
    Mar 28, 2022 at 9:04
  • 1
    @joseLuís Right, but this is a really good option if you already have a dependency on anyhow. Dec 27, 2022 at 18:36

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.