How do I idiomatically convert a bool to an Option or Result in Rust?

一曲冷凌霜 提交于 2020-11-29 04:21:03

问题


It seems there is no way of such one-line conversion using std.

I do not like this kind of verbosity:

match my_bool {
    true => Ok(()),
    false => Err(MyError::False),
}

I would like to use some kind of one-liner, e.g.:

let my_bool = true;
let my_option = my_bool.to_option(MyObject{}); // true => MyObject{}, false => None
let my_result = my_bool.to_result(MyObject{}, MyError{}); // true => MyObject{}, false => MyError{}

What is the shortest piece of code doing that?


回答1:


There is the boolinator crate. It defines the extension trait Boolinator for bool which adds a couple of useful methods. Example:

use boolinator::Boolinator;

my_bool.as_some(MyObject {});                // Option<MyObject>
my_bool.as_result(MyObject {}, MyError {});  // Result<MyObject, MyError>

A true value leads to Some(_) or Ok(_), while a false value leads to None or Err(_).

There is an issue about adding functionality like this to std on the RFCs repository, but it doesn't look like it's happening anytime soon.




回答2:


bool.then_some() does this:

let my_bool = true;
let my_option = my_bool.then_some(MyObject{});
let my_result = my_bool.then_some(MyObject{}).ok_or(MyError{});

At the time of writing, this is still part of the experimental bool_to_option feature.




回答3:


Use an if expression:

if my_bool { Ok(()) } else { Err(MyError::False) }



回答4:


You can use Option::filter:

let my_option = Some(MyObject{}).filter(|_| my_bool);
let my_result = Some(MyObject{}).filter(|_| my_bool).ok_or(MyError{}); 

A true value leads to Some(_) or Ok(_), while a false value leads to None or Err(_). You can do this on stable Rust with no external dependencies.



来源:https://stackoverflow.com/questions/54841351/how-do-i-idiomatically-convert-a-bool-to-an-option-or-result-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!