How to check current positon and turn to next positon in Iterator

#[derive(Debug)]
enum Unit{
    INT(i32),
    STR(String),
    FLOAT(f32)
}
#[derive(Debug)]
struct People{
    name: String,
    elements: Vec<Unit>
}

impl Iterator for People {
    type Item = Unit;
    fn next(&mut self) -> Option<Self::Item> {
        // how to check current position and turn to next position ?
    }
}

fn main(){
    let a1 = Unit::INT(1_i32);
    let a2 = Unit::FLOAT(2.2_f32);
    let a3 = Unit::STR("abc".to_string());
    let peo1 = People{
        name: "Tina".to_string(),
        elements: vec![a1, a2, a3]
    };
}

I wanna iter the People struct, display all the Unit(s) she/he have,
how to check current positon and turn to next positon in Iterator?

Usually, you don't implement Iterator directly for a data structure that owns its items. That would require the data structure to keep track of the iteration state, which is undesirable (it conflates storage with iteration, and it makes it impossible to have multiple iterators to the same collection simultaneously).

You would instead implement the IntoIterator trait, defining a specialized iterator type. In your case, you could just piggyback on the already existing iterators for slices and vectors:

impl IntoIterator for People {
    type Item = Unit;
    type IntoIter = std::vec::IntoIter<Unit>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.into_iter()
    }
}

impl<'a> IntoIterator for &'a People {
    type Item = &'a Unit;
    type IntoIter = core::slice::Iter<'a, Unit>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.iter()
    }
}
7 Likes

Thanks so much, H2CO3,

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.