Why should I prefer `Option::ok_or_else` instead of `Option::ok_or`?

前端 未结 3 877
甜味超标
甜味超标 2020-12-03 11:31

I just saw the following change in a pull request:

- .ok_or(Error::new(ErrorKind::Other, \"Decode error\"));
+ .ok_o         


        
3条回答
  •  眼角桃花
    2020-12-03 11:57

    In addition to performance implications, more complex arguments in ok_or might yield unexpected results if one is not careful enough; consider the following case:

    fn main() {
        let value: Option = Some(1);
    
        let result = value.ok_or({ println!("value is not Some!"); 0 }); // actually, it is
    
        assert_eq!(result, Ok(1)); // this holds, but "value is not Some!" was printed
    }
    

    This would have been avoided with ok_or_else (and the same goes for other *_or_else functions), because the closure is not evaluated if the variant is Some.

提交回复
热议问题