如何在 Rust 中对向量的每个元素应用函数(类似 map)?
大家好!我刚开始学习 Rust,从 Python 转过来,在处理向量时遇到了问题。
在 Python 中,我习惯这样做:
```python
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
```
或者用列表推导式,更方便。
在 Rust 中,我写了类似这样的代码:
```rust
fn main() {
let numbers = vec![1, 2, 3, 4];
// 我想得到一个新的向量,包含数字的平方
let squared: Vec = numbers.map(|x| x * x).collect();
println!("{:?}", squared);
}
```
编译器报错:
```
error[E0599]: no method named `map` found for struct `Vec` in the current scope
```
我明白 Rust 不是 Python,这里类型检查更严格。但该如何处理向量的每个元素呢?我听说过迭代器,但不完全理解如何使用。请告诉我如何正确地对每个元素应用函数,以得到一个新的向量?我需要一个名称。