rust-lang / rust-lang/rust-clippy
Incorrect suggestion for `unnecessary_to_owned` when moving into `'static` closure
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
Clippy gives an incorrect suggestion for a unnecessary_to_owned lint, when the item being cloned is moved into a closure which has a 'static lifetime.
Reproducer
Running Clippy against this code, which compiles succesfully:
fn do_something(x: &str) { println!("{x}") }
fn handle_func(f: impl Fn() + 'static) { f() }
fn main() {
let items = vec!["foo".to_string(), "bar".to_string(), "baz".to_string()];
for x in items.iter().cloned() {
handle_func(move || do_something(&x))
}
}
Gives this suggestion:
warning: unnecessary use of `cloned`
--> src/main.rs:7:11
|
7 | for x in items.iter().cloned() {
| ^^^^^^^^^^^^^^^^^^^^^
|
= 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
help: use
|
7 | for x in items.iter() {
| ~~~~~~~~~~~~
help: remove this `&`
|
8 - handle_func(move || do_something(&x))
8 + handle_func(move || do_something(x))
|
Doing this gives the following compilation error:
error[[E0597]](https://doc.rust-lang.org/stable/error-index.html#E0597): `items` does not live long enough
--> src/main.rs:7:11
|
7 | for x in items.iter() {
| ^^^^^^^^^^^^ borrowed value does not live long enough
8 | handle_func(move || do_something(x))
| ------------------------------------ argument requires that `items` is borrowed for `'static`
9 | }
10 | }
| - `items` dropped here while still borrowed
If handle_func does not have the 'static lifetime bound on the closure, Clippy's suggestion is valid.
Version
rustc 1.67.0-nightly (b28d30e1e 2022-12-06)
binary: rustc
commit-hash: b28d30e1e3c2b90fd08b7dd79d8e63884d1e0339
commit-date: 2022-12-06
host: aarch64-apple-darwin
release: 1.67.0-nightly
LLVM version: 15.0.4
Additional Labels
@rustbot label +I-suggestion-causes-error
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 reproducer in the issue and inspect the implementation and regression tests for the unnecessary_to_owned lint. Run Clippy on the shown code, then ensure the suggested rewrite remains compilable when the closure has a 'static bound and add coverage for this case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100