about summary refs log tree commit diff
diff options
context:
space:
mode:
authorSteve Klabnik <steve@steveklabnik.com>2015-07-07 09:19:26 -0400
committerSteve Klabnik <steve@steveklabnik.com>2015-07-07 09:19:26 -0400
commitf29b565e2d73cd0d5e732d6b04bcbb19ce4363b4 (patch)
tree72addb1144bae57e4b7ee9195aa2230f824b844d
parent26f0cd5de7f71a0db0bb3857ce49a11cd0f7d876 (diff)
downloadrust-f29b565e2d73cd0d5e732d6b04bcbb19ce4363b4.tar.gz
rust-f29b565e2d73cd0d5e732d6b04bcbb19ce4363b4.zip
Describe lifetime syntax for impl
Fixes #26375
-rw-r--r--src/doc/trpl/lifetimes.md29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/doc/trpl/lifetimes.md b/src/doc/trpl/lifetimes.md
index 11d651c5778..8e02367b921 100644
--- a/src/doc/trpl/lifetimes.md
+++ b/src/doc/trpl/lifetimes.md
@@ -101,6 +101,8 @@ the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut
 i32` as ‘a mutable reference to an i32’ and `&'a mut i32` as ‘a mutable
 reference to an `i32` with the lifetime `'a`’.
 
+# In `struct`s
+
 You’ll also need explicit lifetimes when working with [`struct`][structs]s:
 
 ```rust
@@ -137,6 +139,33 @@ x: &'a i32,
 uses it. So why do we need a lifetime here? We need to ensure that any reference
 to a `Foo` cannot outlive the reference to an `i32` it contains.
 
+## `impl` blocks
+
+Let’s implement a method on `Foo`:
+
+```rust
+struct Foo<'a> {
+    x: &'a i32,
+}
+
+impl<'a> Foo<'a> {
+    fn x(&self) -> &'a i32 { self.x }
+}
+
+fn main() {
+    let y = &5; // this is the same as `let _y = 5; let y = &_y;`
+    let f = Foo { x: y };
+
+    println!("x is: {}", f.x());
+}
+```
+
+As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat
+`'a` twice, just like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>`
+uses it.
+
+## Multiple lifetimes
+
 If you have multiple references, you can use the same lifetime multiple times:
 
 ```rust