Purpose of `impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I`?


#1

Hi,

Can someone tell me what is the purpose of the following implementation in src/libcore/iter/traits.rs?

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
    fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}

#2

It’s so you can pass a mutable reference to a DoubleEndedIterator as a DoubleEndedIterator.


#3

Could you please show some example code to demonstrate this?


#4

This will fail to compile because Trait is not implemented for &mut A. If you uncomment the commented line it’ll work.


#5

Awesome demonstration! It definitely shows what problem the impl is trying to solve. Thanks Steven.


#6

Here’s a way to use &mut I of an iterator to iterate a part of it. playground

fn main() {
    let mut r = 0..10;
    
    // take the back 3 elements
    for elt in (&mut r).rev().take(3) {
        print!("{}, ", elt);
    }
    println!("");
    
    // print the rest
    for elt in r {
        print!("{}, ", elt);
    }
    println!("");
}

output:

9, 8, 7, 
0, 1, 2, 3, 4, 5, 6,