Is there a way to simplify converting an Option into a Result without a macro?

前端 未结 1 1133
予麋鹿
予麋鹿 2020-12-11 00:11

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

impl Foo {
    pub fn get(&\'a mut self, key: &a         


        
相关标签:
1条回答
  • 2020-12-11 00:18

    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)
    }
    
    0 讨论(0)
提交回复
热议问题