Lifetime elision in impl

Minimum Rust version: 1.31

When writing impl blocks, you can now elide lifetime annotations in somesituations.

Consider a trait like MyIterator:

  1. trait MyIterator {
  2. type Item;
  3. fn next(&mut self) -> Option<Self::Item>;
  4. }

In Rust 2015, if we wanted to implement this iterator for mutable referencesto Iterators, we'd need to write this:

  1. impl<'a, I: MyIterator> MyIterator for &'a mut I {
  2. type Item = I::Item;
  3. fn next(&mut self) -> Option<Self::Item> {
  4. (*self).next()
  5. }
  6. }

Note all of the 'a annotations. In Rust 2018, we can write this:

  1. impl<I: MyIterator> MyIterator for &mut I {
  2. type Item = I::Item;
  3. fn next(&mut self) -> Option<Self::Item> {
  4. (*self).next()
  5. }
  6. }

Similarly, lifetime annotations can appear due to a struct that containsreferences:

  1. struct SetOnDrop<'a, T> {
  2. borrow: &'a mut T,
  3. value: Option<T>,
  4. }

In Rust 2015, to implement Drop on this struct, we'd write:

  1. impl<'a, T> Drop for SetOnDrop<'a, T> {
  2. fn drop(&mut self) {
  3. if let Some(x) = self.value.take() {
  4. *self.borrow = x;
  5. }
  6. }
  7. }

But in Rust 2018, we can combine elision with the anonymous lifetime andwrite this instead.

  1. impl<T> Drop for SetOnDrop<'_, T> {
  2. fn drop(&mut self) {
  3. if let Some(x) = self.value.take() {
  4. *self.borrow = x;
  5. }
  6. }
  7. }