Lifetime elision
Rust has rules that allow lifetimes to be elided in various places where the compiler can infer a sensible default choice.
Lifetime elision in functions
In order to make common patterns more ergonomic, lifetime arguments can be
elided in function item, function pointer, and closure trait signatures.
The following rules are used to infer lifetime parameters for elided lifetimes.
It is an error to elide lifetime parameters that cannot be inferred. The
placeholder lifetime, '_
, can also be used to have a lifetime inferred in the
same way. For lifetimes in paths, using '_
is preferred. Trait object
lifetimes follow different rules discussed
below.
- Each elided lifetime in the parameters becomes a distinct lifetime parameter.
- If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.
In method signatures there is another rule
- If the receiver has type
&Self
or&mut Self
, then the lifetime of that reference toSelf
is assigned to all elided output lifetime parameters.
Examples:
Default trait object lifetimes
The assumed lifetime of references held by a trait object is called its default object lifetime bound. These were defined in RFC 599 and amended in RFC 1156.
These default object lifetime bounds are used instead of the lifetime parameter
elision rules defined above when the lifetime bound is omitted entirely. If
'_
is used as the lifetime bound then the bound follows the usual elision
rules.
If the trait object is used as a type argument of a generic type then the containing type is first used to try to infer a bound.
- If there is a unique bound from the containing type then that is the default
- If there is more than one bound from the containing type then an explicit bound must be specified
If neither of those rules apply, then the bounds on the trait are used:
- If the trait is defined with a single lifetime bound then that bound is used.
- If
'static
is used for any lifetime bound then'static
is used. - If the trait has no lifetime bounds, then the lifetime is inferred in
expressions and is
'static
outside of expressions.
Note that the innermost object sets the bound, so &'a Box<dyn Foo>
is still
&'a Box<dyn Foo + 'static>
.
'static
lifetime elision
Both constant and static declarations of reference types have implicit
'static
lifetimes unless an explicit lifetime is specified. As such, the
constant declarations involving 'static
above may be written without the
lifetimes.
Note that if the static
or const
items include function or closure
references, which themselves include references, the compiler will first try
the standard elision rules. If it is unable to resolve the lifetimes by its
usual rules, then it will error. By way of example: