Does Rust have a way to apply a function/method to each element in an array or vector?

前端 未结 2 446
無奈伤痛
無奈伤痛 2020-12-10 10:56

Does the Rust language have a way to apply a function to each element in an array or vector?

I know in Python there is the map() function which performs

2条回答
  •  再見小時候
    2020-12-10 11:17

    Since Rust 1.21, the std::iter::Iterator trait defines a for_each() combinator which can be used to apply an operation to each element in the collection. It is eager (not lazy), so collect() is not needed:

    fn main() {
        let mut vec = vec![1, 2, 3, 4, 5];
        vec.iter_mut().for_each(|el| *el *= 2);
        println!("{:?}", vec);
    }
    

    The above code prints [2, 4, 6, 8, 10] to the console.

    Rust playground

提交回复
热议问题