Working with range in vec!

The below code is working fine:

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

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

vec![1..5] isn't part of Rust syntax.

Perhaps you meant:

let v: i32 = (1i32 ..= 5).map(|x| x.pow(2)).sum();
1 Like

vec![1..5] is valid Rust syntax - it creates a Vec<Range<i32>> with a single element consisting of the range 1..5.


How can I use 'iter' or 'map' with it!

This question was cross-posted to Stack Overflow