此代码可以正常工作:
fn main() {
let v: i32 = vec![1, 2, 3, 4, 5].iter().map(|&x: &i32| x.pow(2)).sum();
println!("{}", v);
}
我尝试将vec![1, 2, 3, 4, 5]
替换为vec![1..5]
,但是iter
和map
无效:
error[E0631]: type mismatch in closure arguments
--> src/main.rs:2:36
|
2 | let v: i32 = vec![1..5].iter().map(|&x: &i32| x.pow(2)).sum();
| ^^^ ------------------- found signature of `for<'r> fn(&'r i32) -> _`
| |
| expected signature of `fn(&std::ops::Range<{integer}>) -> _`
error[E0599]: no method named `sum` found for type `std::iter::Map<std::slice::Iter<'_, std::ops::Range<{integer}>>, [closure@src/main.rs:2:40: 2:59]>` in the current scope
--> src/main.rs:2:61
|
2 | let v: i32 = vec![1..5].iter().map(|&x: &i32| x.pow(2)).sum();
| ^^^
|
= note: the method `sum` exists but the following trait bounds were not satisfied:
`std::iter::Map<std::slice::Iter<'_, std::ops::Range<{integer}>>, [closure@src/main.rs:2:40: 2:59]> : std::iter::Iterator`
`&mut std::iter::Map<std::slice::Iter<'_, std::ops::Range<{integer}>>, [closure@src/main.rs:2:40: 2:59]> : std::iter::Iterator`
答案 0 :(得分:1)
像1..5
这样的范围已经是一个迭代器,因此您不必调用iter()
来创建一个迭代器:
let v: i32 = (1..5).map(|x: i32| x.pow(2)).sum();
还请注意,引用已消失,因为此迭代器遍历值。
如果您绝对需要Vec
,则需要先将范围收集到其中:
let v: i32 = (1..5)
.collect::<Vec<i32>>()
.iter()
.map(|&x: &i32| x.pow(2))
.sum();