2021-09-13
Elision rules are as follows:
Each elided lifetime in input position becomes a distinct lifetime parameter.
Even though there are two inputs that have different lifetimes according to the rules of lifetime elision, it is safe to elide the lifetime here as no reference is returned.
pub fn do_something(input: &str, other_input: &str) {
}
If there is exactly one input lifetime position (elided or not), that lifetime is assigned to all elided output lifetimes.
pub fn first_do_something(input: &str) -> (&str, &str) {
(input, input)
}
If there are multiple input lifetime positions, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.
struct Config {
name: String
}
impl Config {
fn name(&self, other_useless_val: &str) -> &str {
&self.name // <- same lifetime as &self
}
}
Otherwise, it is an error to elide an output lifetime.
Given the following:
fn lifetimes<'a: 'b, 'b>(a: &'a str, b: &'b str) {}
Read this as "'a
will live for at least as long as 'b
, rather than 'a
has
to outlive 'b
. It's a small distinction but a relevant one.
See: lifetime coercion