Skip to content

Commit d35c81f

Browse files
committed
Fix description of lifetime elision in impl
Fixes #84
1 parent 58fbfb0 commit d35c81f

File tree

1 file changed

+64
-9
lines changed

1 file changed

+64
-9
lines changed

src/rust-2018/ownership-and-lifetimes/lifetime-elision-in-impl.md

Lines changed: 64 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,74 @@
22

33
![Minimum Rust version: nightly](https://img.shields.io/badge/Minimum%20Rust%20Version-nightly-red.svg)
44

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.
77

8-
In Rust 2015:
8+
Consider a trait like `MyIterator`:
99

1010
```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+
}
1315
```
1416

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:
1619

1720
```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

Comments
 (0)