There are three different lifetime specifiers on an impl:
impl<\'a> Type<\'a> {
fn my_function(&self) -> &\'a u32 {
self.x
Paraphrasing the Rust code:
impl<'a>
"If you give me a lifetime..." (the compiler normally supplies this based on context when using the type)
Type<'a> {
"...I'll describe how to implement Type<'a>
". So Type
probably contains references (which need a lifetime).
fn my_function(&self) -> &'a u32 {
"...and given a reference to Type<'a>
, you call my_function()
to get a reference to a u32
with lifetime 'a
." Note that the lifetime of the &self
reference is not directly tied to 'a
; it can be shorter (but usually not longer than 'a
, since a type can't outlive contained references).
In the second case:
impl TextEditor {
"Here's how to implement a non-lifetime parametric type TextEditor
..."
pub fn get_text<'a>
"Given a lifetime 'a
which you can choose (it's an input parameter)..."
(&'a self)
"...and a reference to a TextEditor
which lives for at least 'a
.."
-> &'a String {
"...you can call the get_text
method and receive a borrowed reference to a String
which lives for the same time."
In more practical terms, this really means that the String
is reborrowed directly from the TextEditor
- as long as that String
reference is alive, the &self
borrow is considered to still be active and you won't be able to take any &mut
references.