Skip to content

New Lint: match_single_field #7122

Open
@camsteffen

Description

@camsteffen

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

Metadata

Metadata

Labels

A-lintArea: New lintsL-styleLint: Belongs in the style lint group

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions