rust-lang / rust-lang/rust-clippy
Lifetime error following `unnecessary_to_owned` going from `.to_vec().into_iter()` to `.iter().copied()`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
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
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
Start with the unnecessary_to_owned lint and the reproducer in the issue, then run Clippy against the shown Rust code. The fix is complete when the lint does not suggest replacing .to_vec().into_iter() with .iter().copied() in this lifetime-sensitive case and the reported lifetime error is avoided.
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
- Mostly clear
- Newbie friendliness
- 45/100