Lifetime elision in impl
When writing impl
blocks, you can now elide lifetime annotations in somesituations.
Consider a trait like MyIterator
:
trait MyIterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
In Rust 2015, if we wanted to implement this iterator for mutable referencesto Iterators
, we'd need to write this:
impl<'a, I: MyIterator> MyIterator for &'a mut I {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
(*self).next()
}
}
Note all of the 'a
annotations. In Rust 2018, we can write this:
impl<I: MyIterator> MyIterator for &mut I {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
(*self).next()
}
}
Similarly, lifetime annotations can appear due to a struct that containsreferences:
struct SetOnDrop<'a, T> {
borrow: &'a mut T,
value: Option<T>,
}
In Rust 2015, to implement Drop
on this struct, we'd write:
impl<'a, T> Drop for SetOnDrop<'a, T> {
fn drop(&mut self) {
if let Some(x) = self.value.take() {
*self.borrow = x;
}
}
}
But in Rust 2018, we can combine elision with the anonymous lifetime andwrite this instead.
impl<T> Drop for SetOnDrop<'_, T> {
fn drop(&mut self) {
if let Some(x) = self.value.take() {
*self.borrow = x;
}
}
}