如何在 Rust 中惯用地将 bool 转换为 Option 或 Result? [英] How do I idiomatically convert a bool to an Option or Result in Rust?
问题描述
使用 std
似乎没有办法进行这种单行转换.
It seems there is no way of such one-line conversion using std
.
我不喜欢这种冗长:
match my_bool {
true => Ok(()),
false => Err(MyError::False),
}
我想用单线,例如:
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{}
最短的代码是什么?
推荐答案
这个答案有些过时了.从 Rust 1.50 开始,您可以使用内置的 bool::then
.有关详细信息,请参阅下面的其他答案.
This answer is somewhat outdated. Starting with Rust 1.50, you can use the built-in bool::then
. See the other answers below for more information.
有 boolinator
crate.它定义了 扩展特征 Boolinator
bool
添加了几个有用的方法.示例:
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>
true
值导致 Some(_)
或 Ok(_)
,而 false
值导致 None
或 Err(_)
.
A true
value leads to Some(_)
or Ok(_)
, while a false
value leads to None
or Err(_)
.
有一个 关于将这样的功能添加到 std
在 RFC 存储库中,但它看起来不会很快发生.
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.
这篇关于如何在 Rust 中惯用地将 bool 转换为 Option 或 Result?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!