Rust 是否有办法将函数/方法应用于数组或向量中的每个元素? [英] Does Rust have a way to apply a function/method to each element in an array or vector?

查看:65
本文介绍了Rust 是否有办法将函数/方法应用于数组或向量中的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 语言是否有办法将函数应用于数组或向量中的每个元素?

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

我知道在 Python 中有执行此任务的 map() 函数.在 R 中有 lapply()tapply()apply() 函数也可以做到这一点.

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.

是否有一种既定的方法可以在 Rust 中对函数进行向量化?

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

推荐答案

Rust 有 Iterator::map,所以你可以:

Rust has Iterator::map, so you can:

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

然而,Iterators 是惰性的,所以它本身不会做任何事情.你可以添加一个 .collect() 到最后用新元素创建一个新向量,如果这是你想要的:

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);

执行副作用的标准方法是使用 for 循环:

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]

如果你真的想要函数式风格,你可以使用 .for_each() 方法:

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]

这篇关于Rust 是否有办法将函数/方法应用于数组或向量中的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆