Skip to content

Suggest replacing pattern matching with map or map_err #8436

@lkts

Description

@lkts

What it does

This is in some way an extension to redundant_pattern_matching lint. The lint flags pattern matching that can be trivially converted to map or map_err invocations.

Lint Name

extend redundant_pattern_matching or prefer_map_over_pattern_match

Category

style

Advantage

  • Code is shorter
  • Less indentation
  • Reduced boilerplate of mapping enum cases as is
  • In my experience this is a common pattern people new to Rust follow and it helps to discover the alternative

Drawbacks

Depending on the code base this lint can be very intrusive.

Example

let foo = match some_result_returning_fn() {
    Ok(val) => Ok(some_fn(val)),
    Err(e) => Err(e)
}

Could be written as:

let foo = some_result_returning_fn().map(some_fn);
let foo = match some_option_returning_fn() {
    Some(val) => Some(some_fn(val)),
    None => None
}

Could be written as:

let foo = some_option_returning_fn().map(some_fn);
let foo = match some_result_returning_fn() {
    Ok(val) => Ok(val),
    Err(e) => Err(some_fn(e))
}

Could be written as:

let foo = some_option_returning_fn().map_err(some_fn);

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messages

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions