Is there a way to simplify converting a parameter to a result without a macro?

Suppose 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
    {
        // ...
    }
}

and I have to call him 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) => s,
            None => return Result::Err("no ini item".to_string()),
        }
    }
}

Is it possible to remove code duplication without implementing macros?

+4
source share
1 answer

Methods ok_orand ok_or_elseconvert Optionto Results, and the macro try!automates the template associated with the early return Err. So you would do something like:

fn new() -> Result<Boo, String> {
    let item1 = try!(section.get("item1").ok_or("no item1"));
    let item2 = try!(section.get("item2").ok_or("no item2"));
    // whatever processing...
    Ok(final_result)
}
+12
source

All Articles