Is there a more concise way to format .expect() message?

后端 未结 3 1594
情书的邮戳
情书的邮戳 2020-12-20 14:10

I currently have to use this to format a .expect() message:

fn main() {
    let x: Option<&str&g         


        
3条回答
  •  生来不讨喜
    2020-12-20 14:28

    To avoid the unnecessary overhead of formatting and allocating a String in the case of an Ok, you can convert the Option to a Result and then unwrap it:

    fn main() {
        let x: Option<&str> = None;
        x.ok_or_else(|| format!("the world is ending: {}", "foo"))
            .unwrap();
    }
    

提交回复
热议问题