Using generic iterators instead of specific list types

后端 未结 3 897
生来不讨喜
生来不讨喜 2020-12-05 14:53

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.

3条回答
  •  春和景丽
    2020-12-05 15:33

    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.

提交回复
热议问题