HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayfunctionhavemethoddoeselementvectorwayrusteach

Problem

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 this task. In R there is the lapply(), tapply(), and apply() functions that also do this.

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

Solution

Rust has Iterator::map, so you can:

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


However, Iterators are lazy so this won't do anything by itself. You can tack a .collect() onto the end to make a new vector with the new elements, if that's 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 perform side effects is to use a for loop:

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


If the side effect should modify the values in place, you can use an iterator of mutable references:

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 the functional style, you can use the .for_each() method:

let mut some_vec = vec![1, 2, 3];
some_vec.iter_mut().for_each(|i| *i *= 2);
println!("{:?}", some_vec); // [2, 4, 6]

Code Snippets

some_vec.iter().map(|x| /* do something here */)
let some_vec = vec![1, 2, 3];
let doubled: Vec<_> = some_vec.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
let some_vec = vec![1, 2, 3];
for i in &some_vec {
    println!("{}", i);
}
let mut some_vec = vec![1, 2, 3];
for i in &mut some_vec {
    *i *= 2;
}
println!("{:?}", some_vec); // [2, 4, 6]
let mut some_vec = vec![1, 2, 3];
some_vec.iter_mut().for_each(|i| *i *= 2);
println!("{:?}", some_vec); // [2, 4, 6]

Context

Stack Overflow Q#32872013, score: 90

Revisions (0)

No revisions yet.