如何在Rust中习惯性地将布尔值转换为Option或Result? [英] How do I idiomatically convert a bool to an Option or Result in Rust?

查看:93
本文介绍了如何在Rust中习惯性地将布尔值转换为Option或Result?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有办法使用 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{}

执行此操作最短的代码是什么?

What is the shortest piece of code for doing that?

推荐答案

此答案有些过时了.从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 板条箱.它定义了扩展特征 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 的问题> 在RFCs信息库中,但看起来它不会很快发生.

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中习惯性地将布尔值转换为Option或Result?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆