Pre-RFC: syntax sugar for `matches!`

I like your examples. They make me feel like any form of method-position macro would be the optimal solution.

let b = "hello world!".contains(|c| c.matches!('a'..='z'));
iter
    .map(...)
    .filter(...)
    .map(...)
    .next()
    .matches!(None)



This kind of syntax was deemed suboptimal in another thread (I don’t remember which one) (Edit: It was in a few of these 160+ comments on GitHub) because it binds something on the right hand side which is rather confusing:

x matches Some(y) || return 0;
println!("{}", y);

I could personally perhaps live with something along the lines of

if !let Some(y) = x { return 0 }
println!("{}", y);

but that’s not too pretty either. Maybe another method macro

let y = x.unwrap_or_else!{
    return 0;
};

might come in handy in a bunch of situations. Or use try blocks?


There’s also this terrible wonderful solution for the time being:

let y = if let Some(y) = x { y } else {
    return 0
};
println!("{}", y);

I guess with a sophisticated macro that ... well ... guesses based on case (or is there any other way for proc macros perhaps?) which of the identifiers are variables and which ones are constants, that automates this extraction process so you can write

let_or_else!{Some(y) = x {
    return 0
}}

still ugly...., perhaps:

let_!{ Some(y) = x, else:
    return 0
}
1 Like
x matches Some(y) || return 0;
println!("{}", y);

This causes some weird lifetime and scoping issues. Would y be a reference to x? What would its lifetime be?

What about this?

let b: bool = x matches Some(y);

You could tie y to live as long as b. That would make this invalid:

x matches Some(y) || return 0;
println!("{}", y);

But this would be valid:

let b = x matches Some(y);
if b {
    return 0;
}
println!("{}", y);

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.