rust-lang / rust-lang/rust-clippy
`bind_instead_of_map` should suggest removing `Result::and_then` call when possible
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
bind_instead_of_map transforms certain Result::and_then calls into Result::map, but in the example I provide below, it'd be better to just remove and_then altogether. Sure enough, if I apply clippy's suggestion to replace and_then(|v| Ok(v)) with map(|v| v), the fixed code then triggers map_identity, which tells me to remove the map` call clippy just bullied me into adding.
Reproducer
I tried this code:
fn returns_result() -> Result<(), ()> {
Ok(())
}
fn main() {
returns_result().and_then(|v| Ok(v)).unwrap();
}
I expected to see this happen:
Clippy should suggest removing the and_then altogether, yielding returns_result().unwrap();
Instead, this happened:
Clippy suggests using map:
warning: using `Result.and_then(|x| Ok(y))`, which is more succinctly expressed as `map(|x| y)`
--> src/main.rs:6:5
|
6 | returns_result().and_then(|v| Ok(v)).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `returns_result().map(|v| v)`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#bind_instead_of_map
= note: `#[warn(clippy::bind_instead_of_map)]` on by default
...which triggers map_identity:
warning: unnecessary map of the identity function
--> src/main.rs:6:21
|
6 | returns_result().map(|v| v).unwrap();
| ^^^^^^^^^^^ help: remove the call to `map`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_identity
= note: `#[warn(clippy::map_identity)]` on by default
Version
Reproduced on play.rust-lang.org today, which is currently Rust 1.86, Clippy 0.1.86
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the bind_instead_of_map and subsequent map_identity diagnostics using the Rust example in the issue, then trace the lint's suggestion logic from that behavior. Done means the original and_then(|v| Ok(v)) case suggests removing the call entirely, without introducing a map that triggers map_identity.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 40/100