HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModerate

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howidiomaticallybooloptionconvertresultrust

Problem

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 a one-liner, for example:
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?

Solution

This answer is somewhat outdated. Starting with Rust 1.50, you can use the built-in bool::then. See the other answers above for more information.

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
my_bool.as_result(MyObject {}, MyError {});  // Result


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.

Code Snippets

use boolinator::Boolinator;

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

Context

Stack Overflow Q#54841351, score: 20

Revisions (0)

No revisions yet.