Skip to content

Unhelpful lifetime error on .clone() refers to &&T, could suggest adding Clone #40699

Closed
@kw217

Description

@kw217

In code that works with boxed closures (e.g., futures code), it is common to clone an argument so that it can be moved into the closure. If the argument is passed by reference, clone() will clone the value if there is a Clone implementation, otherwise it will pointlessly clone the reference.

If the Clone implementation is not present, rustc reports E0495 quite unhelpfully.

Please could rustc spot this and suggest adding a Clone implementation? I think the signature is an invocation of clone() at &T when the type compatibility being checked is &&T.

Example:

// Uncomment the derive to make this compile.
//#[derive(Clone)]
struct Foo(String);

fn bar(p: &Foo) -> Box<Fn() -> ()> {
    let p = p.clone();
    let f = move || baz(&p);
    Box::new(f)
}

fn baz(_: &Foo) {}

pub fn main() {
    let foo = Foo("foo".to_string());
    let closure = bar(&foo);
    closure()
}

Error message:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
 --> doubleref.rs:5:15
  |
5 |     let p = p.clone();
  |               ^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 4:35...
 --> doubleref.rs:4:36
  |
4 |   fn bar(p: &Foo) -> Box<Fn() -> ()> {
  |  ____________________________________^ starting here...
5 | |     let p = p.clone();
6 | |     let f = move || baz(&p);
7 | |     Box::new(f)
8 | | }
  | |_^ ...ending here
note: ...so that types are compatible (expected &&Foo, found &&Foo)
 --> doubleref.rs:5:15
  |
5 |     let p = p.clone();
  |               ^^^^^
  = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[[email protected]:6:13: 6:28 p:&Foo]` will meet its required lifetime bounds
 --> doubleref.rs:7:5
  |
7 |     Box::new(f)
  |     ^^^^^^^^^^^

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsP-lowLow priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions