rust-lang / rust-lang/rust-clippy

unnecessary_to_owned causes type mismatch

Open
#8,929 9 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive I-suggestion-causes-error
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

Clippy will suggest turning .to_vec().into_iter() into .iter().copied() even when doing so causes a type mismatch later in the function

Lint Name

unnecessary_to_owned

Reproducer

I tried this code:

full code

let mut foos_left = FOOS.to_vec().into_iter().filter(make_filter(true, 'b'));
foos_left = foos_left
    .collect::<Vec<_>>()
    .into_iter()
    .filter(make_filter(false, 'z'));

I saw this happen:

warning: unnecessary use of `to_vec`
  --> src/main.rs:17:25
   |
17 |     let mut foos_left = FOOS.to_vec().into_iter().filter(make_filter(true, 'b'));
   |                         ^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `FOOS.iter().copied()`
   |
   = note: `#[warn(clippy::unnecessary_to_owned)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_to_owned

I expected to see this happen:
Nothing; applying the change causes a type mismatch error because the type of foos_left changes

Version
rustc 1.63.0-nightly (e09449220 2022-05-31)
binary: rustc
commit-hash: e0944922007e1bb4fe59809293acf4364410cccc
commit-date: 2022-05-31
host: x86_64-unknown-linux-gnu
release: 1.63.0-nightly
LLVM version: 14.0.4
Additional Labels

@rustbot label +l-suggestion-causes-error

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

Begin with the linked Rust Playground reproducer and the unnecessary_to_owned lint. Compare the suggested iter().copied() form with the original to identify why reassignment changes the type. Done means the lint no longer suggests a change that produces a type mismatch, with regression coverage for the reproducer.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.