Trait bounds non-moving iterator?


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:

Any pointers on how I can make this work?


Could you use the bound?

pub struct Foo<Children> where for<'a> &'a Children: IntoIterator<Item = &'a u32> {
    children: Children

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?


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

1 Like

@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

1 Like