Hi all. I'm playing with iterators trying to get comfortable with them in Rust.
I want to build an iterator for heterogeneous Vector which does unboxing before returning the reference. My code compiles for constant Refs, but fails with strange message about lifetimes for &mut.
It basically says:
error: lifetime may not live long enough
--> src/bin/debox_ref_and_mut.rs:46:13
|
38 | impl<'a, T: ?Sized> Iterator for DeBoxIterMut<'a, T> {
| -- lifetime `'a` defined here
39 | type Item=&'a mut T;
40 | fn next(self: &mut Self) -> Option<&'a mut T> {
| - let's call the lifetime of this reference `'1`
...
46 | Some(elt)
| ^^^^^^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
What puzzles the most, is that I got Mut version by just copy-pasting and adding the mut keywords in several places. Whats the reason for that lifetime issue?
// This Works
struct DeBoxIter<'a, T: ?Sized> {
abs: &'a Vec<Box<T>>,
pos: usize
}
impl<'a, T: ?Sized> DeBoxIter<'a, T> {
fn from_vec(vec: &'a Vec<Box<T>>) -> DeBoxIter<'a, T> {
DeBoxIter{abs: vec, pos:0}
}
}
impl<'a, T: ?Sized> Iterator for DeBoxIter<'a, T> {
type Item=&'a T;
fn next(self: & mut Self) -> Option<&'a T> {
if self.pos >= self.abs.len() {
None
} else {
let elt = self.abs[self.pos].as_ref();
self.pos += 1;
Some(elt)
}
}
}
// This doesn't
struct DeBoxIterMut<'a, T: ?Sized> {
abs: &'a mut Vec<Box<T>>,
pos: usize
}
impl<'a, T: ?Sized> DeBoxIterMut<'a, T> {
fn from_vec(vec: &'a mut Vec<Box<T>>) -> DeBoxIterMut<'a, T> {
DeBoxIterMut{abs: vec, pos:0}
}
}
impl<'a, T: ?Sized> Iterator for DeBoxIterMut<'a, T> {
type Item=&'a mut T;
fn next(self: &mut Self) -> Option<&'a mut T> {
if self.pos >= self.abs.len() {
None
} else {
let elt = self.abs[self.pos].as_mut();
self.pos += 1;
Some(elt)
}
}
}
Here is the playground link: