File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 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
101101i32` as ‘a mutable reference to an i32’ and ` &'a mut i32` as ‘a mutable
102102reference to an ` i32 ` with the lifetime ` 'a ` ’.
103103
104+ # In ` struct ` s
105+
104106You’ll also need explicit lifetimes when working with [ ` struct ` ] [ structs ] s:
105107
106108``` rust
@@ -137,6 +139,33 @@ x: &'a i32,
137139uses it. So why do we need a lifetime here? We need to ensure that any reference
138140to 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+
140169If you have multiple references, you can use the same lifetime multiple times:
141170
142171``` rust
You can’t perform that action at this time.
0 commit comments