error: lifetime may not live long enough
--> src/next_lifetime.rs:9:9
|
5 | impl<'a> Iterator for A<'a> {
| -- lifetime `'a` defined here
...
8 | fn next(&mut self) -> Option<Self::Item> {
| - let's call the lifetime of this reference `'1`
9 | Some(&mut self.a[0])
| ^^^^^^^^^^^^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
Think about what would happen if you .collect() this iterator: you'd have multiple mutable references to the same place. So, the code you posted must not compile because it is unsound.
It won't compile if you add a proper incrementing index, either; not because it would be unsound but because the compiler isn't clever enough to determine that it is sound.
The right thing to do is to make use of the std code that has already been written for you. That will be the safe and efficient option. Keep the total amount of unsafe code in the world small. If you really wanted to write a mutable slice iterator from scratch, you could use raw pointers — but it's actually possible to make a slice iterator with careful use of pattern matching.
impl<'a> Iterator for A<'a> {
type Item = &'a mut u8;
fn next(&mut self) -> Option<Self::Item> {
if let [item, rest @ ..] = std::mem::take(&mut self.a) {
self.a = rest;
Some(item)
} else {
None
}
}
}