Hello Everyone,
Iterators are clearly a powerful tool. I recall reading once that fold
is the universal constructor. Any transformation can be expressed in terms of a fold
. If that's true, then all the more power to iterators.
When first delving into Rust, I took a look at how the standard library implemented an iterator for Vec
. I suppose one way of describing that experience: "drinking water from a fire-hose". I got wet and did not take much in.
In trying to find inspiration for how to design my current project, I thought I would take another crack at how to unify and consolidate my understanding of how Vec
, slice
and array
iterate over T
.
I have attached a schematic of what I hope is a useful resource for the community at large. To make sure it's so, I wonder if you might take a look to share some of your thoughts on how it might be improved. It's dense, but reflects the implementation as best as I could tell. Notwithstanding, I'm hoping I was able to pull a few patterns that resonate with others.
last updated Feb 16, 2021
Roughly speaking, the goals were to:
- better understand the "namesake" of
into_iter()
when used with&Vec<T>
compared toiter()
- understand how
IntoIterator
andIterator
work together for these types (it seems so unnecessarily complicated; what don't I know?) - The three types are "same but different"; being so similar, especially when borrowing, how do their differences "play out" when iterating over T elements (e.g., similarly, arrays in C are performant in how they use pointers; how does it play here?)
- Identify "where the action happens" and why so much indirection
- Finally, I wanted to understand how traits interact with what I've been calling "go-between" structures in a way that seems powerful and productive (e.g.,
Iter
andIterMut
); what is their role and how to think more generally about them?
The chart describes the following (for T
, &T
and &mut T
):
Vec<T> -> Iterator
slice -> Iterator
array -> Iterator
It describes the single path to a "move" semantic and the choices for the "borrows" (read-only and mut).
My intention is to provide early Rustaceans the benefit of my prior efforts, and to develop the presentation to something that resonates with the community at large. Ideally, it would be fodder to how the Rust Book
introduces and develops the use of iterators and more generally as one of the ways to unify our data types to benefit from code-reuse.
Thank you in advance for any comments/questions!
PS: I could only include a .png
; please feel free to reach out to request a .pdf
version of the chart.