Rfcs: Possible new feature: Option::is_any()

Created on 15 Feb 2020  ·  4Comments  ·  Source: rust-lang/rfcs

Hi.

Suppose the following code:

pub struct QueryableTaxpayer {
    ...
    pub manager: Option<bool>,

currently, it is possible to do something like this:

let is_manager: bool = matches!(taxpayer.manager, Some(true));

however, what do you think about something like this?

let is_manager: bool = taxpayer.manager.is_any::<bool>(true);

or even:

let is_manager: bool = taxpayer.manager.is_some(true);

I'm not a Rust specialist, however, the is_any() implementation maybe it would be something like this:

impl<T> Option<T> {
    ...
    pub fn is_any(&self, val: T) -> bool {
        matches!(*self, Some(val))
    }

Thank you!

Most helpful comment

I don't see how .is_any(x) is "sweeter" than == Some(x)

let is_manager = taxpayer.manager.is_any(true);
let is_manager = taxpayer.manager == Some(true);
let is_manager = taxpayer.manager.eq(&Some(true)); // another spelling of ==
let is_manager = taxpayer.manager.contains(&true); // see comment below

If the method takes a _closure_ instead of values then it could have the advantage of lazily evaluating the compared term.

let is_manager = taxpayer.is_some_with(|tp| tp.is_manager());
let is_manager = taxpayer.map_or_default(|tp| tp.is_manager()); // a better name?
let is_manager = taxpayer.map_or(false, |tp| tp.is_manager());

All 4 comments

Isn’t this the same as == Some(val)?

Isn’t this the same as == Some(val)?

@SimonSapin yes, but with some "syntax-sugar". :smiley: Btw, it is something like an Option::is_some(), however, allowing to pass a value (Some(val)) to be compared (instead of Some(_)).

I don't see how .is_any(x) is "sweeter" than == Some(x)

let is_manager = taxpayer.manager.is_any(true);
let is_manager = taxpayer.manager == Some(true);
let is_manager = taxpayer.manager.eq(&Some(true)); // another spelling of ==
let is_manager = taxpayer.manager.contains(&true); // see comment below

If the method takes a _closure_ instead of values then it could have the advantage of lazily evaluating the compared term.

let is_manager = taxpayer.is_some_with(|tp| tp.is_manager());
let is_manager = taxpayer.map_or_default(|tp| tp.is_manager()); // a better name?
let is_manager = taxpayer.map_or(false, |tp| tp.is_manager());

Isn't it Option::contains?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rudolfschmidt picture rudolfschmidt  ·  3Comments

3442853561 picture 3442853561  ·  3Comments

marinintim picture marinintim  ·  3Comments

onelson picture onelson  ·  3Comments

3442853561 picture 3442853561  ·  3Comments