Hello , I have a basic data structure that behaves much like a vector (with a few key differences that prohibits using actual vectors, hashsets or treesets). Since it's such a basic building block of the computation I would like to easily swap different implementations. So a trait is the obvious answer.
Something like:
But I'm not satisfied with just IntoIterator, I need iter() to be implemented.
Since there is no trait for that, I need to qualify IntoIterator for &Self somehow.
What is the syntax? Can i actually do it or should i just require fn iter(...) -> ... in my trait?
trait BorrowIter<'a> {
type Item;
type IntoIter: Iterator<Item = Self::Item>;
fn iter(&'a self) -> Self::IntoIter;
}
impl<'a, T: 'a> BorrowIter<'a> for T where &'a T: IntoIterator {
type Item = <&'a T as IntoIterator>::Item;
type IntoIter = <&'a T as IntoIterator>::IntoIter;
fn iter(&'a self) -> Self::IntoIter { self.into_iter() }
}
fn test(v: &'static impl BorrowIter<'static>) {
println!("len = {}", v.iter().count());
}
fn main() {
test(&[2, 3, 5]);
}
It is hard to get rid of this lifetime. Consider: what happens if &'static SomeContainer implements IntoIterator while &'other_lt SomeContainer does not?