I don't understand this lifetime error
⚓ Rust 📅 2026-01-08 👤 surdeus 👁️ 3Consider the following snippet of code:
fn create_closure() -> impl FnOnce(&mut usize) {
let cloj = |a: &mut usize| {};
cloj
}
This compiles. Now I thought, why even name the type of a, the compiler should be able to infer it from the function signature. So I did:
fn create_closure() -> impl FnOnce(&mut usize) {
let cloj = |a| {};
cloj
}
rust-analyzer confirms that the inferred type of a is &mut usize. However, this does not compile. The error is:
error: implementation of `FnOnce` is not general enough
--> src/main.rs:4:5
|
4 | cloj
| ^^^^ implementation of `FnOnce` is not general enough
|
= note: closure with signature `fn(&'2 mut usize)` must implement `FnOnce<(&'1 mut usize,)>`, for any lifetime `'1`...
= note: ...but it actually implements `FnOnce<(&'2 mut usize,)>`, for some specific lifetime `'2`
It seems that the lifetime of the closure is different when I name the type of the argument vs when I don't. However, in the error, the compiler seems to be able to to tell me "what kind of type/lifetime I need", so why does it not infer it then?
Can someone explain in detail what's happening here? Would love to learn more about this.
Thanks!
1 post - 1 participant
🏷️ Rust_feed