Closed
Description
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)
| ^^^^^^^^^^^