I\'m very new to Rust, coming from C# / Java / similar.
In C# we have IEnumerable
that can be used to iterate almost any kind of array or list.
Here is the full version of Map, and here is the function that builds it.
A minimal implementation would look something like
fn map(i: I, f: F) -> Map where
F: FnMut(E) -> B,
I: Iterator-
{
Map {iter: i, f: f}
}
pub struct Map {
iter: I,
f: F,
}
impl Iterator for Map where F: FnMut(I::Item) -> B {
type Item = B;
fn next(&mut self) -> Option {
self.iter.next().map(|a| (self.f)(a))
}
}
Playpen link. Note that the map
used inside the iterator is the method on Option
; this isn't recursively defined!
It's not too convenient to write, but boy is it fast!
Now, to write this for an arbitrary "enumerable" type one would change map
to
fn map(i: I, f: F) -> Map where
F: FnMut(E) -> B,
I: IntoIterator-
{
Map {iter: i.into_iter(), f: f}
}
IntoIterator
is basically IEnumerable
, only instead of GetEnumerator
there's into_iter
.