How to implement Iterator

I have a Vec in my Struct, I want to iterate all the data in inner Vec but not consuming the wrapper struct after the iteration.

    pub struct Series<T> {
        length: usize,
        contain: Vec<T>,
    }

    let series = Series::new(vec![1, 2, 3]);

    for i in &series {
        println!("{}", i);
    }

    println!("Serics : {:?}", series);

After some coding, I use SeriesIterator to do this, but the code looks a little complex. Could anyone show me how to do this the simplest way?

Here is the code:

If you're okay committing to the Vec and exposing this to consumers of your type, you can just return the iterator Vec uses.

Or, you can wrap that iterator to maintain flexibility should you need to change the implementation in the future.

(Edit: Not shown, you may wish to implement various other iterator traits like DoubleEndedIterator if you go the wrapping route. Or not, again to maintain flexibility. It's a performance + utility vs flexibility tradeoff.)

Thanks @quinedot That's a great help, I also there's an answer in stackoverflow

btw, as for performance, are both ways the same?

The std iterator may in some cases be able to optimize better because it implements the TrustedLen trait, which you will not be able to implement. Besides this, they are equivalent.