#Adding lifetimes to an `IntoIterator` impl

10 messages · Page 1 of 1 (latest)

pastel knot
#

I'm being told that the lifetimes are unconstrained. I know the &'a Vec<usize> can only live as long as Indices itself, but I'm not sure how to signify this.

pub struct Indices {
    indices: Vec<usize>,
}

pub struct IndicesIterator<'a> {
    indices: &'a Vec<usize>,
}

impl<'a> IntoIterator for Indices {
    type Item = usize;
    type IntoIter = IndicesIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        IndicesIterator {
            indices: &self.indices,
        }
    }
}
#

Adding lifetimes to an IntoIterator impl

fringe mortar
#

implement it for &'a Indices

scenic falcon
#

Yes, and the reason you have to is because of the Into in IntoIterator — it consumes its input so if you want to implement it and produce a borrowing iterator, you must start with a borrow of the data, not ownership of the data.

pastel knot
#

Hmm. So if I was to implement IntoIterator it would be more appropriate to move the Vec?

#

Guessing I have to implement Iterator instead if I want just to iterate over the values (or rather, it would have to be references to the values)

unique temple
#

You'd implement for &'a Indices, that's enough

pastel knot
#

Thank you,sorry for the delay

#

Is this the way one would generally implement iterator traits for a wrapper over a collection?