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

前端 未结 3 886
甜味超标
甜味超标 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:51

    The signature of std::io::Error::new is

    fn new(kind: ErrorKind, error: E) -> Error 
    where
        E: Into>, 
    

    This means that Error::new(ErrorKind::Other, "Decode error") allocates memory on the heap because error needs to be converted into Box to be of any use.

    Consequently, this pull request removes unneeded memory allocation/deallocation when the Result value is Result::Ok.

提交回复
热议问题