Implementing iterators best practices

I have some sample code on the playground that demonstrates my best effort to implement Iterator, IntoIterator and FromIterator on a struct that contains a Vec. I included both a non-generic and a generic version: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3966644b4cd51c0a8b07351db654ee8d

Can someone please look over it and tell me if this code matches up with best practices or if there can be improvements? For example, I have looked over other tutorials like https://dev.to/dandyvica/yarit-yet-another-rust-iterators-tutorial-46dk which use std::slice::Iter which I think might be more efficient than my approach but I have been unable to get that to compile.

1 Like

I would also suggest wrapping slice::Iter. Can you show an example with the problems you faced?

1 Like

I created a new playground post: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f31bf5a86a345d863dd763395b3ad9f4
This one does not compile but is my best effort at a non-generic non-consuming Iterator. I am relatively new to rust and I think my problem boils down to lifetime references but I am unsure how to solve it. Any help would be appreciated.

Luke

Here's a version that compiles, I didn't modify much, mostly added/removed lifetimes.

I just removed DogVecIter.inner since it wasn't used, so this type could become a newtype, I left it like this in case you need inner in your real code.

1 Like

Thank you, that was exactly the guidance that I needed.