Request: guide to writing mutating iterators


#1

Writing iterators seems like one of the trickier aspects of creating data structures in Rust, especially when it’s a mutating iterator.

Rather than trying to get my broken code working via StackOverflow questions, I’d love to read a common-practices guide to writing iterators. Does something like this currently exist?

Here are a couple iterator resources I’m currently aware of:


#2

Agree a decent resource for iterators would be nice
You can add this as well http://doc.rust-lang.org/core/iter/

There is a c++ lib which has some more documentation which helps a little https://github.com/ryanhaining/cppitertools
I am sure there are much better resources though. Hope this helps anyway.


#3

What, exactly, do you mean by mutating iterators?

Iterators that return &mut references? Iterators that support special mutation operations (insert, remove) during iteration?

If the former I don’t really see how it’s any different than writing an & iterator? You might need to toss in some unsafe to tell the compiler “I got this”, but logic-wise there’s nothing particularly special going on.


#4

I meant iterators that return &mut references.

I agree that the logic for writing mutable iterators is not different, but as you note some amount of unsafe code will likely be required to make the Rust compiler happy. That’s the sort of thing I’d like to see a guide to. (Such a guide might also cover how best to avoid code duplication between mutating and non-mutating iterators.)


#5

Yeah there aren’t really good solutions to this problem.

If you’re composing on top of something that already provides iterators, then you can generalize over IntoIterator like BTreeMap and BList do. Otherwise I’ve seen macros and the eubious hack of transmuting one type of reference to another. I also discuss some of the general issues in a couple posts.


#6

Yep, that is my impression as well. There isn’t a way to implement external iterators yet that is general & concise & pretty.

I’d say that’s all the more reason to have a somewhat official guide for current best practices so that each Rust programmers doesn’t undertake a private spirit journey when implementing iterators. :slight_smile:


#7

Yup I ran into this as well. https://github.com/mspiegel/rust-yaar. I’m trying to learn as much Rust as possible without writing unsafe code. That may be a habit I need to break.