How can a range be used in a Vec?

Has*_*sef 8 rust

This code works fine:

fn main() {
    let v: i32 = vec![1, 2, 3, 4, 5].iter().map(|&x: &i32| x.pow(2)).sum();
    println!("{}", v);
}
Run Code Online (Sandbox Code Playgroud)

I tried to replace the vec![1, 2, 3, 4, 5] with vec![1..5] but iter and map did not work:

fn main() {
    let v: i32 = vec![1, 2, 3, 4, 5].iter().map(|&x: &i32| x.pow(2)).sum();
    println!("{}", v);
}
Run Code Online (Sandbox Code Playgroud)

I've also asked this question on the Rust user's forum.

Flo*_*mer 12

像这样的范围1..5已经是一个迭代器,因此您不必调用iter()来创建迭代器:

let v: i32 = (1..5).map(|x: i32| x.pow(2)).sum();
Run Code Online (Sandbox Code Playgroud)

另请注意,引用消失了,因为此迭代器迭代值。

如果您绝对需要 a Vec,则需要首先将范围收集到其中:

let v: i32 = (1..5)
    .collect::<Vec<i32>>()
    .iter()
    .map(|&x: &i32| x.pow(2))
    .sum();
Run Code Online (Sandbox Code Playgroud)

  • 你的第二个例子可以简化:`let v: i32 = (1..5).collect::&lt;Vec&lt;i32&gt;&gt;().iter().map(|x| x.pow(2)).sum ();` (2认同)