rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

suggest `map` or `map_err` when only the `Ok()` or `Err()` values are changed, respectively, in a pattern match

Open darklyspaced opened this issue 2 years ago • 2 comments

What it does

Checks for usage of a match of if let expression where only the Ok() or Err() values are modified; suggests the use of map or map_err instead.

Advantage

  • Readability, usage of Result::map and Result::map_err is more concise

Drawbacks

None that I can think of.

Example

#[derive(PartialEq, Debug)]
struct Wrapper(i32);

let x = match fallible() {
    Ok(a) => Ok(Wrapper(a)),
    Err(err) => Err(err),
};

Could be written as:

# #[derive(PartialEq, Debug)]
# struct Wrapper(i32);

let x = fallible().map(|ok| Wrapper);

Extensions

This would also apply to other pattern matches. For example, if let Ok(x) and modifying just the x value. We could also extend this to map_or_else in the case that both the Ok() and Err() variants are modified.

darklyspaced avatar Jul 22 '23 08:07 darklyspaced

@rustbot claim

darklyspaced avatar Jul 28 '23 03:07 darklyspaced

As a past master of the unnecessary match on Result (I've since gotten better), I definitely support the existence of this lint -- I'd like clippy to check my old code for cases where past-me was being a goose. @darklyspaced, are you still interested in implementing this? Otherwise, I could have a crack at it.

mpalmer avatar Apr 28 '24 03:04 mpalmer

yes, feel to have a go at it. i don't have much time nowadays unfortunately.

darklyspaced avatar May 14 '24 01:05 darklyspaced

@rustbot claim

mpalmer avatar May 14 '24 05:05 mpalmer