rust-lang / rust-lang/rust-clippy

New lint suggestion: advise replacement of `map` + `take_while` + `map` by `map_while`

Open
#8,048 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

First suggestion for clippy lint, sorry if I missed something

What it does

Detects usages of this form (link):

let a = [-1i32, 4, 0, 1];

let mut iter = a.iter()
               .map(|x| 16i32.checked_div(*x))
               .take_while(|x| x.is_some())
               .map(|x| x.unwrap());

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);
Categories (optional)
  • Kind: once stable, either style or complexity, though similar lints are in pedantic (but they don't involve an extra .unwrap() in their to-fix form)

Advantages:

  • One method call instead of three
  • Removes an unwrap call (and so a lot of panic machinery when compiling for debug, maybe even for release if the compiler doesn't see it's always true)
Drawbacks
  • Will only be valid for 1.57+
  • Closures may be a little harder to read/write and the transformation may not be obvious (I haven't done any research about it)
Example
let a = [-1i32, 4, 0, 1];

let mut iter = a.iter()
               .map(|x| 16i32.checked_div(*x))
               .take_while(|x| x.is_some())
               .map(|x| x.unwrap());

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);

Could be written as:

let a = [-1i32, 4, 0, 1];

let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The examples and linked Iterator::map_while documentation define the target transformation; begin by checking the Rust 1.57 compatibility constraint and how Clippy categorizes similar lints. Done means the pattern is recognized without changing iterator behavior, with coverage for the shown cases and an agreed lint category.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.