rust-lang / rust-lang/rust-clippy

New Lint: `match_single_field`

Open
#7,122 2 comments 0 reactions 1 assignee View on GitHub

@peter-shen-dev is already working on this.

Since Dec 6, 2021.

A-lint L-style
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Finds match or if let expressions where only one inner field is actually being matched. This could be a struct field, a tuple struct field or an array element (but not slices).

Categories
  • Kind: style

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

It is simpler.

Drawbacks

None.

Example
struct Strct { bar: Option<u32> }
struct Tup(Option<u32>, u32);

fn fun(struct: Strct, arr: [Option<u32>; 2], tup: Tup) {
	  if let Strct { bar: Some(_), .. } = strct { todo!() }
 
	  match arr {
	      [.., None] => todo!(),
	      [.., Some(_)] => todo!(),
	  }

	  if let Tup(Some(_), _) = tup { todo!() }
}

Could be written as:

fn fun(struct: Strct, arr: [Option<u32>; 2], tup: Tup) {
	  if let Some(_) = strct.bar { todo!() }

	  match arr[1] {
	      None => todo!(),
	      Some(_) => todo!(),
	  }

	  if let Some(_) = tup.0 { todo!() }
}

Note: It is possible for the reduced match to look like if let 1 = x[0] which is better expressed as if x[0] == 1.

Another lint name idea: reducible_match, reducible_match_scrutinee

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.