Skip to content

Lifetime error following unnecessary_to_owned going from .to_vec().into_iter() to .iter().copied() #14711

Open
@ginnyTheCat

Description

@ginnyTheCat

Summary

As closures don't allow to specify that the returntype has the same lifetime as the input, it's in this case required to clone the input and return a owned value. In this case the iterator would borrow b and therefore clippy's suggestion to replace it with .iter().copied() results in a lifetime error.

error: lifetime may not live long enough
 --> src/main.rs:8:13
  |
8 |     run(|b| b.iter().copied().map(|c| c.to_ascii_uppercase()));
  |          -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
  |          ||
  |          |return type of closure is Map<Copied<std::slice::Iter<'2, u8>>, {closure@src/main.rs:8:35: 8:38}>
  |          has type `&'1 [u8]`
  |
help: consider adding 'move' keyword before the nested closure
  |
8 |     run(|b| b.iter().copied().map(move |c| c.to_ascii_uppercase()));
  |

Lint Name

unnecessary_to_owned

Reproducer

I tried this code:

fn run<F: Fn(&[u8]) -> I, I: Iterator<Item = u8>>(f: F) {
    for x in f(b"abc") {
        println!("{x}");
    }
}

fn main() {
    run(|b| b.to_vec().into_iter().map(|c| c.to_ascii_uppercase()));
}

I saw this happen:

warning: unnecessary use of `to_vec`
 --> src/main.rs:8:13
  |
8 |     run(|b| b.to_vec().into_iter().map(|c| c.to_ascii_uppercase()));
  |             ^^^^^^^^^^^^^^^^^^^^^^ help: use: `b.iter().copied()`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_to_owned
  = note: `#[warn(clippy::unnecessary_to_owned)]` on by default

warning: `tmp` (bin "tmp") generated 1 warning

I expected to see this happen:
Nothing at all

Version

rustc 1.88.0-nightly (74509131e 2025-04-29)
binary: rustc
commit-hash: 74509131e85a97353c67c503ea32e148a56cf4bd
commit-date: 2025-04-29
host: x86_64-unknown-linux-gnu
release: 1.88.0-nightly
LLVM version: 20.1.2

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions