Confused about the anonymous lifetime `'_`
⚓ Rust 📅 2026-02-06 👤 surdeus 👁️ 11Hi everyone, I've been trying to wrap my head around the semantics of the anonymous lifetime '_. I've originally learned about those from Jon's video and I don't think he's right about how they interact.
He claims that these two function signatures are the same:
fn foo(x: &str, y: &'_ str) -> &'_ str {
todo!()
}
fn bar<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
todo!()
}
Problem is that I couldn't get foo to compile in any edition so I don't think he's right about that.
I understand his explanation as follows:
- in argument position, the anonymous lifetime means a fresh unnamable lifetime, that it can be used to "discard" lifetimes from consideration during inference (because its unnamable?). Yet I've never been able to use it in that way.
- in return position it means lifetime inference (?) - I don't think is a very good word to describe what happens because in rust there's no inference across function signatures, and compiler does not analyse code to determine which lifetime it being returned.
In my opinion Its more of a "placeholder" for a lifetime parameter in a type annotation where there's only one possible value for it, as in:
struct Foo<'a>(&'a u32);
fn baz(x: &u32) -> Foo<'_> { Foo(x) }
This compiles just fine.
This however is just explicit annotation that a borrow occurs, but the underlying mechanism is the lifetime elision - which dictates in which cases lifetimes can be trivially inferred. Its not the anonymous lifetime which causes inference - its the lifetime elision rules, the need to use the anonymous lifetime here is necessary to make the borrow explicit.
I found very little information about this topic in authoritative sources life rust reference.
How do you understand / use this language feature?
3 posts - 3 participants
🏷️ Rust_feed