Skip to content

Latest commit

 

History

History
106 lines (82 loc) · 4.14 KB

File metadata and controls

106 lines (82 loc) · 4.14 KB

Summary

Add methods to bool for converting to an Option<T>, given a t: T, where true maps to Some(t) and false maps to None, abstracting the following common pattern in Rust.

if some_condition {
    Some(t)
} else {
    None
}

Motivation

This is an extremely common pattern in Rust code, but is quite verbose, taking several lines to achieve something with only two important data: the bool and the T. If we instead collapse the expression on to a single line, the legibility of the code is reduced. In addition, chaining a conversion from a bool to an Option<T> is inconvenient in this form and usually requires binding an extra variable to remain readable. Abstracting this common pattern into a method will make code more readable and require less repetitive typing on the user's part.

A method for converting from bool to Option<T> has been requested several times in the past [1] [2] [3] in the past and shows a significant desire from users.

Reference-level explanation

Following this proposal, we will add two methods to bool:

impl bool {
    fn then<T>(self, t: T) -> Option<T> {
        if self {
            Some(t)
        } else {
            None
        }
    }

    fn then_with<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
        if self {
            Some(f())
        } else {
            None
        }
    }
}

The primitive type bool currently has no methods, so it will be necessary to add support similarly to other primitive types that do have methods, like char.

Drawbacks

Save the usual drawbacks of adding a new method to the standard library, there are no drawbacks.

Rationale and alternatives

The implementations here are the only reasonable ones.

The following names have been suggested in the past. The choice in this proposal has been made to avoid possible confusion (e.g. avoiding a name that suggests a conversion from bool to Option<()> rather than Option<T>), and to be consist with existing naming conventions (e.g. then_with rather than then_do to be consist with methods such as get_or_insert_with), but ultimately comes down to personal preference.

This functionality could instead be provided by a crate (e.g. boolinator), but this functionality is commonly desired and an obvious candidate for the standard library, where an external crate for such simple functionality is not convenient.

Prior art

  • Jane Street's OCaml Core library contains a some_if method on Option.

Unresolved questions

None.

Future possibilities

Methods for converting from a bool to a Result<T, E>, e.g. then_else and then_else_with, would be obvious candidates for inclusion into the standard library, which could also be included as an addendum to this proposal if desire is expressed.