Trait bounds non-moving iterator?

#1

I want to define a generic struct that has a member that can provide an iterator that i can call repeatedly to iterate over its collection (non moving).

pub struct<Children> {
    children: Children
}

Basically I want my struct’s children be repeatedly iteratable, so I can have a method for my struct:

pub fn doit(&self) {
    for c in &self.children {
        //do something with c
    }
}

So that children could be a Vec<> or some linked list that can be iterated over, or something else…

I’m assuming I need to make a reference to my generic parameter implement IntoIterator?

this is the closest i’ve come so for:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c632f63de7ee98af479a680762d94708

Any pointers on how I can make this work?

#2

Could you use the bound?

pub struct Foo<Children> where for<'a> &'a Children: IntoIterator<Item = &'a u32> {
    children: Children
}
4 Likes
#3

So just a question; if I were to need a kind of 'self lifetime in certain situations I could use HRTBs? Such as this one that you just showed?

#4

Yes, it works because HRTB assserts that a bound must work for all lifetimes.

1 Like
#5

@KrishnaSannasi once again, thanks a ton!

The &'a for the items, oops, that should have been obvious.

for anyone coming later, here is the playground that implements this https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ffe1bf8caca97a9184215b71367faa34

1 Like