Skip to content

non_canonical_clone_impl sugg fails due to lifetime #15577

@matthiaskrgr

Description

@matthiaskrgr

Using the following flags

--force-warn clippy::non_canonical_clone_impl

this code:

struct Weird<'a>(&'a i32);

impl Clone for Weird<'_> {
    fn clone(&self) -> Self {
        println!("clone() called");
        Weird(self.0)
    }
}

impl Copy for Weird<'static> {}

fn main() {
    let local = 1;
    let _ = [Weird(&local)].clone();
}

caused the following diagnostics:

    Checking _snippet_0 v0.1.0 (/tmp/icemaker_global_tempdir.W9mV5T7suTWy/icemaker_clippyfix_tempdir.EE0EO9b2vI7W/_snippet_0)
warning: non-canonical implementation of `clone` on a `Copy` type
 --> src/main.rs:4:29
  |
4 |       fn clone(&self) -> Self {
  |  _____________________________^
5 | |         println!("clone() called");
6 | |         Weird(self.0)
7 | |     }
  | |_____^ help: change this to: `{ *self }`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl
  = note: requested on the command line with `--force-warn clippy::non-canonical-clone-impl`

warning: `_snippet_0` (bin "_snippet_0") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.22s

However after applying these diagnostics, the resulting code:

struct Weird<'a>(&'a i32);

impl Clone for Weird<'_> {
    fn clone(&self) -> Self { *self }
}

impl Copy for Weird<'static> {}

fn main() {
    let local = 1;
    let _ = [Weird(&local)].clone();
}

no longer compiled:

    Checking _snippet_0 v0.1.0 (/tmp/icemaker_global_tempdir.W9mV5T7suTWy/icemaker_clippyfix_tempdir.EE0EO9b2vI7W/_snippet_0)
error: lifetime may not live long enough
 --> src/main.rs:4:31
  |
4 |     fn clone(&self) -> Self { *self }
  |              -----            ^^^^^ copying this value requires that `'1` must outlive `'static`
  |              |
  |              has type `&Weird<'1>`

error: could not compile `_snippet_0` (bin "_snippet_0" test) due to 1 previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `_snippet_0` (bin "_snippet_0") due to 1 previous error

Version:

rustc 1.91.0-nightly (91ee6a405 2025-08-26)
binary: rustc
commit-hash: 91ee6a4057ce4bf1ab6d2f932cae497488d67c81
commit-date: 2025-08-26
host: x86_64-unknown-linux-gnu
release: 1.91.0-nightly
LLVM version: 21.1.0

Metadata

Metadata

Assignees

Labels

I-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions