Using powi with Vecc! elements

The below code worked with me correctly, and gave the result as 14

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


I’m trying to replace the x * x by powi(2) so I tried both options below, but none of them worked!

let v1 : i32 = vec![1,2,3].iter().map(|x| x.powi(2)).sum();
let v2 : i32 = vec![1,2,3].iter().map(|&x| &x.powi(2)).sum();

powi is a method on floating point numbers. You probably want to use pow. Also it appears Rust has some issues inferring the type of integer you’re using. You can force the type for example like so: |&x: &i32|.

1 Like

tried this code:

let v : i32 = vec![1,2,3].iter().map(|&x: &i32| &x.pow(2)).sum();

and got this error:

temporary value does not live long enough

Why are you returning a reference from your closure?

1 Like

Thanks, below worked fine:

let v : i32 = vec![1,2,3].iter().map(|&x: &i32| x.pow(2)).sum();

This question was cross-posted to Stack Overflow.