Skip to content

catch-all in match expression #12465

@andrewbanchich

Description

@andrewbanchich

What it does

One of the biggest benefits of match expressions is they are exhaustive. However, programmers often add catch-all arms when they shouldn't.

At the time of writing the catch-all, this enum:

enum Animal { Monkey, Frog, Caecilian }

might be matched on like:

match animal { Animal::Monkey => println!("it's a mammal"), _ => println!("it's an amphibian") }

and be correct. However, since this is a catch-call, the user is opting out of the benefits of exhaustive pattern matching. If they update the definition of Animal to be:

enum Animal { Monkey, Frog, Caecilian, Parrot }

then their program will silently start thinking that parrots are amphibians.

This lint will recommend each type be written explicitly:

match animal { Animal::Monkey => println!("it's a mammal"), Animal::Frog | Animal::Caecilian => println!("it's an amphibian") }

Advantage

Exhaustive pattern matching allows for much more fearless refactoring.

Drawbacks

More verbose. Also, sometimes a catch-all is the most correct way to express something.

Example

match animal { Animal::Monkey => println!("it's a mammal"), _ => println!("it's an amphibian") }

Could be written as:

match animal { Animal::Monkey => println!("it's a mammal"), Animal::Frog | Animal::Caecilian => println!("it's an amphibian") }

@rustbot claim

Metadata

Metadata

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions