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

≯℡__Kan透↙ 提交于 2019-12-01 14:39:54

问题


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?


回答1:


We do have 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 do something without allocating is to use a for loop:

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

or if you'd like to modify 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 the functional style, you can use the foreach method from the itertools crate.




回答2:


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



来源:https://stackoverflow.com/questions/32872013/does-rust-have-a-way-to-apply-a-function-method-to-each-element-in-an-array-or-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!