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

Is there a way in Rust to apply a function to each element of an array or vector?

I know that in Python there is a map() function that performs this task. In R there are functions lapply() , tapply() and apply() which also do this.

Is there an established way to vectorize a function in Rust?

+8
source share
2 answers

We have Iterator::map , so you can:

 some_vec.iter().map(|x| /* do something here */) 

However, Iterator lazy, so it will not do anything on its own. You can .collect() at the end to create a new vector with new elements, if that is what you want:

 let some_vec = vec![1, 2, 3]; let doubled: Vec<_> = some_vec.iter().map(|x| x * 2).collect(); println!("{:?}", doubled); 

The standard way to do something without highlighting is to use a for loop:

 let some_vec = vec![1, 2, 3]; for i in &some_vec { println!("{}", i); } 

or if you want to change the values ​​in place:

 let mut some_vec = vec![1, 2, 3]; for i in &mut some_vec { *i *= 2; } println!("{:?}", some_vec); // [2, 4, 6] 

If you really want a functional style, you can use the foreach method from the itertools box.

+14
source

Starting with Rust 1.21, the std::iter::Iterator for_each() defines for_each() which can be used to apply the operation to each element in an array or vector. This is impatient (not lazy), so collect() not needed:

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

The code above displays [2, 4, 6, 8, 10] on the console.

Rusty playground

+5
source

All Articles