有没有一种方法,以简化选项转换成结果没有一个宏?

问题描述 投票:10回答:1

我有这样的事情(真正的功能是从Ini::Section::get rust-ini):

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

我有好几次把它叫做:

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,
    };
}

要删除代码膨胀,我可以写这样的宏:

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

有什么办法去除重复代码没有这个宏实现?

rust
1个回答
22
投票

ok_orok_or_else方法转换到Options Results和?操作自动化早期Err收益相关的样板。

你可以这样做:

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.