Skip to content

New lint: collapsible_guards #7825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
camsteffen opened this issue Oct 15, 2021 · 1 comment · Fixed by #10955
Closed

New lint: collapsible_guards #7825

camsteffen opened this issue Oct 15, 2021 · 1 comment · Fixed by #10955
Labels
A-lint Area: New lints

Comments

@camsteffen
Copy link
Contributor

camsteffen commented Oct 15, 2021

What it does

Detects match guards that can be collapsed into the pattern.

Categories (optional)

  • Kind: complexity

What is the advantage of the recommended code over the original code

It is simpler.

Drawbacks

None.

Example

match x {
    Some(x) if matches!(x, Some(1)) => .., // if matches!
    Some(x) if x == Some(2) => .., // if ==
    x => matches!(x, Some(x) if x == 3), // guard inside matches!
}

Could be written as:

match x {
    Some(Some(1)) => ..,
    Some(Some(2)) => ..,
    x => matches!(x, Some(3)),
}

This lint can share some logic with equatable_if_let. @HKalbasi maybe you'd like to take this?

@camsteffen camsteffen added the A-lint Area: New lints label Oct 15, 2021
@isomer
Copy link

isomer commented Mar 12, 2023

I came here to suggest a similar lint. While I was learning rust I was using guards where I should instead be using ranges eg:

match x {
  n if n < 10 => { ... },
  n if n >= 10 && n <= 20 => { ... },
  n if n > 20 => { ... },
  _ => unreachable!(),
}

and was frustrated that the compiler was requiring the unreachable clause. After looking at this a bit I discovered I really should have been writing this as:

match x {
 0..10 @ n => { ... },
 10..=20 @ n => { ... },
 20.. @ n => { ... },
}

The advantages here are both simplicity, teaching new rustaceans how to use pattern matching better, as well as additional safety guarantees. This also no longer needs the unreachable clause at the end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants