Recipe
Write out the lifetimes a signature leaves out
Use when: you want to know what a signature without lifetime names really promises, or why it is E0106
Goal: the signature with every lifetime written in, or the knowledge that you must choose them yourself
Taught in Elision rules
Quick recipe
-
1
Give each
&in the parameters that has no name its own fresh name:'a,'b, and so on. Count the ones inside tuples and structs too.Example
fn first_field(line: &str, sep: &str) -> &strbecomesfn first_field<'a, 'b>(line: &'a str, sep: &'b str) -> &str.Why: rule 1 treats every elided input lifetime as a separate parameter.
-
2
If there is exactly one input lifetime, write it on every output reference.
Why: rule 2; with one source, the result can only borrow from it.
-
3
If there are several and one is
&selfor&mut self, writeself's lifetime on every output reference.Why: rule 3; a method's result usually borrows from the value it was called on.
-
4
If the output has no lifetime yet, the signature is E0106. Choose the inputs the result really borrows from, as in section 2.
- the result can come from several inputs — give them one shared name.
- the result comes from one input — name only that input and the output.
Why: the rules never read the body, so only you can say where the result comes from.
Common mistakes
- Deciding from the body which input is returned, as if the compiler did too.
- Counting parameters instead of lifetimes.
- Forgetting rule 1 still applies to the inputs you leave unnamed.