How do I cope with lazy iterators?

后端 未结 3 1908
故里飘歌
故里飘歌 2020-12-10 21:58

I\'m trying to sort an array with a map() over an iterator.

struct A {
    b: Vec,
}

#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct          


        
3条回答
  •  鱼传尺愫
    2020-12-10 22:33

    I don't understand why this variation with iter_mut() works fine:

    a.b.iter_mut().find(|b| b == b).map(|b| b.c.sort());
    

    It works because find is not lazy; it's an iterator consumer. It returns an Option not an Iterator. This might be why it is confusing you, because Option also has a map method, which is what you are using here.


    As others have said, map is intended for transforming data, without modifying it and without any other side-effects. If you really want to use map, you can map over the collection and assign it back:

    fn main() {
        let mut a = A { b: Vec::new() };
        let mut b = B { c: vec![5, 2, 3] };
        a.b.push(b);
    
        a.b =
            a.b.into_iter()
                .map(|mut b| {
                    b.c.sort();
                    b
                })
                .collect();
    }
    

    Note that vector's sort method returns (), so you have to explicitly return the sorted vector from the mapping function.

提交回复
热议问题