Skip to content

Commit f29b565

Browse files
committed
Describe lifetime syntax for impl
Fixes #26375
1 parent 26f0cd5 commit f29b565

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/doc/trpl/lifetimes.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut
101101
i32` as ‘a mutable reference to an i32’ and `&'a mut i32` as ‘a mutable
102102
reference to an `i32` with the lifetime `'a`’.
103103

104+
# In `struct`s
105+
104106
You’ll also need explicit lifetimes when working with [`struct`][structs]s:
105107

106108
```rust
@@ -137,6 +139,33 @@ x: &'a i32,
137139
uses it. So why do we need a lifetime here? We need to ensure that any reference
138140
to a `Foo` cannot outlive the reference to an `i32` it contains.
139141

142+
## `impl` blocks
143+
144+
Let’s implement a method on `Foo`:
145+
146+
```rust
147+
struct Foo<'a> {
148+
x: &'a i32,
149+
}
150+
151+
impl<'a> Foo<'a> {
152+
fn x(&self) -> &'a i32 { self.x }
153+
}
154+
155+
fn main() {
156+
let y = &5; // this is the same as `let _y = 5; let y = &_y;`
157+
let f = Foo { x: y };
158+
159+
println!("x is: {}", f.x());
160+
}
161+
```
162+
163+
As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat
164+
`'a` twice, just like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>`
165+
uses it.
166+
167+
## Multiple lifetimes
168+
140169
If you have multiple references, you can use the same lifetime multiple times:
141170

142171
```rust

0 commit comments

Comments
 (0)