I have this (most simplified) piece of code:
fn returns_closure() -> Box<dyn Fn(&u64)> {
let closure = |_| ();
Box::new(closure)
}
This does not compile with a rather unhelpful error message:
error[E0308]: mismatched types
--> src/main.rs:3:5
|
3 | Box::new(closure)
| ^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected type `FnOnce<(&u64,)>`
found type `FnOnce<(&u64,)>`
However, when I don't bind the closure to a variable first, and create it directly in the constructor of the Box, it does compile:
fn returns_closure() -> Box<dyn Fn(&u64)> {
Box::new(|_| ())
}
Why does the first one fail to compile, and what is the difference between the two?
Edit: Emouns answer seems to be correct. I compiled the exact same code with the nightly toolchain (1.52.0), and got a better error:
error: implementation of `FnOnce` is not general enough
--> src/main.rs:3:5
|
3 | Box::new(closure)
| ^^^^^^^^^^^^^^^^^ implementation of `FnOnce` is not general enough
|
= note: closure with signature `fn(&'2 u64)` must implement `FnOnce<(&'1 u64,)>`, for any lifetime `'1`...
= note: ...but it actually implements `FnOnce<(&'2 u64,)>`, for some specific lifetime `'2`