File tree 1 file changed +29
-0
lines changed
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -101,6 +101,8 @@ the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut
101
101
i32` as ‘a mutable reference to an i32’ and ` &'a mut i32` as ‘a mutable
102
102
reference to an ` i32 ` with the lifetime ` 'a ` ’.
103
103
104
+ # In ` struct ` s
105
+
104
106
You’ll also need explicit lifetimes when working with [ ` struct ` ] [ structs ] s:
105
107
106
108
``` rust
@@ -137,6 +139,33 @@ x: &'a i32,
137
139
uses it. So why do we need a lifetime here? We need to ensure that any reference
138
140
to a ` Foo ` cannot outlive the reference to an ` i32 ` it contains.
139
141
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
+
140
169
If you have multiple references, you can use the same lifetime multiple times:
141
170
142
171
``` rust
You can’t perform that action at this time.
0 commit comments