|
2 | 2 |
|
3 | 3 | 
|
4 | 4 |
|
5 |
| -When writing an `impl`, you can mention lifetimes without them being bound in |
6 |
| -the argument list. |
| 5 | +When writing `impl` blocks, you can now elide lifetime annotations in some |
| 6 | +situations. |
7 | 7 |
|
8 |
| -In Rust 2015: |
| 8 | +Consider a trait like `MyIterator`: |
9 | 9 |
|
10 | 10 | ```rust,ignore
|
11 |
| -impl<'a> Iterator for MyIter<'a> { ... } |
12 |
| -impl<'a, 'b> SomeTrait<'a> for SomeType<'a, 'b> { ... } |
| 11 | +trait MyIterator { |
| 12 | + type Item; |
| 13 | + fn next(&mut self) -> Option<Self::Item>; |
| 14 | +} |
13 | 15 | ```
|
14 | 16 |
|
15 |
| -In Rust 2018: |
| 17 | +In Rust 2015, if we wanted to implement this iterator for mutable references |
| 18 | +to `Iterators`, we'd need to write this: |
16 | 19 |
|
17 | 20 | ```rust,ignore
|
18 |
| -impl Iterator for MyIter<'iter> { ... } |
19 |
| -impl SomeTrait<'tcx> for SomeType<'tcx, 'gcx> { ... } |
20 |
| -``` |
| 21 | +impl<'a, I: MyIterator> MyIterator for &'a mut I { |
| 22 | + type Item = I::Item; |
| 23 | + fn next(&mut self) -> Option<Self::Item> { |
| 24 | + (*self).next() |
| 25 | + } |
| 26 | +} |
| 27 | +``` |
| 28 | + |
| 29 | +Note all of the `'a` annotations. In Rust 2018, we can write this: |
| 30 | + |
| 31 | +```rust,ignore |
| 32 | +impl<I: MyIterator> MyIterator for &mut I { |
| 33 | + type Item = I::Item; |
| 34 | + fn next(&mut self) -> Option<Self::Item> { |
| 35 | + (*self).next() |
| 36 | + } |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +Similarly, lifetime annotations can appear due to a struct that contains |
| 41 | +references: |
| 42 | + |
| 43 | +```rust,ignore |
| 44 | +struct SetOnDrop<'a, T> { |
| 45 | + borrow: &'a mut T, |
| 46 | + value: Option<T>, |
| 47 | +} |
| 48 | +``` |
| 49 | + |
| 50 | +In Rust 2015, to implement `Drop` on this struct, we'd write: |
| 51 | + |
| 52 | +```rust,ignore |
| 53 | +impl<'a, T> Drop for SetOnDrop<'a, T> { |
| 54 | + fn drop(&mut self) { |
| 55 | + if let Some(x) = self.value.take() { |
| 56 | + *self.borrow = x; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +But in Rust 2018, we can combine elision with [the anonymous lifetime] and |
| 63 | +write this instead. |
| 64 | + |
| 65 | +```rust,ignore |
| 66 | +impl<T> Drop for SetOnDrop<'_, T> { |
| 67 | + fn drop(&mut self) { |
| 68 | + if let Some(x) = self.value.take() { |
| 69 | + *self.borrow = x; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +[the anonymous lifetime]: the-anonymous-lifetime.html |
0 commit comments