As a historical matter, note that when the borrow checker was first implemented, you had to use lifetime annotations everywhere; lifetime elision was not available.
So, where in modern Rust, you can write something like fn find_thing(&mut self, name: &str) -> &Thing
, in early borrow checker Rust, you'd have to write fn find_thing<'me, 'name>(&'me mut self, &'name name) -> &'me Thing
. Similarly, you couldn't write fn string_len(string: &str) -> usize
, but had to write something like fn string_len<'s>(string: &'s str) -> usize
.
The lifetime elision rules came about because the people working on the language discovered that there's a small number of rules (just 2 for free functions, 3 for methods) that allow the majority of code to be written without explicit lifetime annotations, without accepting code that's ambiguous in the absence of annotations (like my choose_a_string
example above).
Notably, though, because the lifetime elision rules specify a completely mechanical transform from unannotated code to code where every lifetime has an explicit annotation, the borrow checker rules haven't changed with the addition of lifetime elision; the borrow checker works as-if you wrote explicit annotations for everything, it's just that lifetime elision allows it to infer lifetimes.
So, taking my annotated (but using elision) version of choose_a_string
, I wrote the signature:
fn choose_a_string<'retval>(
which_one: &'_ str,
str1: &'retval str,
str2: &'retval str,
) -> &'retval str {
But the borrow checker looks at it as-if I wrote:
fn choose_a_string<'which, 'retval>(
which_one: &'which str,
str1: &'retval str,
str2: &'retval str,
) -> &'retval str {
and has every single lifetime fully annotated at this point.
One thing I recommend to people struggling with lifetimes is spending a bit of time taking Rust that has elided lifetimes, and carefully adding lifetime annotations matching the elision rules until you have no elided lifetimes. Then you can see what the borrow checker sees when it looks at your code - it's not the same as what you wrote because the lifetimes are all annotated.