rust-lang / rust-lang/rust-clippy

`iter.collect::<Vec<_>>().into_iter()` is useless and causes extra work

Open
#16,101 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

Given the pattern iter.collect::<Vec<_>>().into_iter() Clippy should recommend dropping the collect() and into_iter() calls as they cause useless allocations and work to build a Vec which is immediately iterated over and dropped.

I hit this as I wrote some code which was then refactored to introduce this useless Vec construction/destruction and it caused an OOM in production.

NOTE: This cannot be generalized to all collect() calls as some types will deduplicate when collected (e.g. HashSet)

Advantage
  • Removes extra work
  • Removes allocations (can prevent OOMs)
  • Helps the programmer identify a likely mistake (e.g. during refactoring, which is how I hit this)
Drawbacks

This can't easily be generalized from Vec to all types as some types perform non-trivial work during collect() which could affect the subsequent iterator.

Example
let v: Vec<u8> = vec![1, 2, 3];

let v2: Vec<u8> = v.into_iter().collect::<Vec<u8>>().into_iter().map(|x| x * 2).collect();

Could be written as:

let v: Vec<u8> = vec![1, 2, 3];

let v2: Vec<u8> = v.into_iter().map(|x| x * 2).collect();
Comparison with existing lints

I can't find any lint that covers this exact case: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=be7215aaba35a6e279eb551de374d578

Additional Context

Meta employees can see the additional discussion here where folks recommended to post here: https://fb.workplace.com/groups/rust.language/posts/30023410667280829/

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

Start by locating Clippy's existing lint handling for collect and into_iter, then inspect how similar lints define diagnostics and tests. Reproduce the example and verify that the completed lint catches the Vec-specific pattern without generalizing to collections such as HashSet.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.