Ergonomic opposite of `matches!`

I don’t know if it’s that obviously missing. After all, what can you do with negated patterns? Not bind any variables, can you? So it is basically just a boolean test, something that can be expressed with negated matches in a guard. Of course, currently you cannot easily add guards to an if let. However something like

if let Err(err @ not Fatal) = fn_returning_result() { 
    ...
}

first rewritten as

match fn_returning_result() {
    Err(err @ not Fatal) => {
        ...
    }
    _ => (),
}

can then be translated into current Rust syntax by means of

match fn_returning_result() {
    Err(err) if !(matches!(err, Fatal)) => {
        ...
    }
    _ => (),
}

And in the future, something like

if let Err(err) = fn_returning_result() && !(matches!(err, Fatal))  { 
    ...
}

will probably become possible.

Even something like Foo(not Some(not Fatal)) can already be written like this (admitted not very neat)

Foo(inner) if !(matches!(inner, Some(error) if !(matches!(error, Fatal))))

(in this case Foo(None) | Foo(Some(Fatal)) would way less confusing though)

Of yourse we could thing about introducing a general way to turn guards into patterns (which would then automatically give rise to macro-definable negative patterns if you really want them. I think currently more obvious shortcomings of Rust’s pattern matching are for example that it’s impossible to write patterns that look into Rc or Box.

1 Like

I'd prefer to write it as

match fn_returning_result() {
    Err(Fatal) => { /* nothing */ }
    Err(err) => { /* not Fatal */ }
    Ok(_) => {}
}

Which shows that "not" is a built-in feature of the ordering of the match arms.

If we nest not it seems like our grammar can get quite complicated. A pattern that is for example: (1, not 2, 3, not 4) etc could actually have some use? I'd fear that we run into implementation issues with allowing to express things that might be hard to implement.

Well, variables bindings with variable @ not pattern should at least be possible, as used in the examples (?).

Note that all these re-writes again "suffer" from the !matches! problem OP highlighted. (Disclaimer: FWIW, I'm not overly bothered by that, as it can be made more readable by parentheses, like above, or spaces.)

From previous discussions I understood that match arms are not supposed to have strict ordering.

That must be a misunderstanding, because they do.

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