Quick question about vec sum

why this works:

pub fn square_of_sum(n: u32) -> u32 {
let list: Vec = (1..n+1).collect();
let mut num: u32 = list.iter().sum();
num = num.pow(2);
num
}

and this doesn't:

pub fn square_of_sum(n: u32) -> u32 {
let num: u32 = (1..n+1).collect().iter().sum().pow(2);
num

}

It's just inference that is unable to infer what to collect() into and what to sum() up. If you nudge type inference a bit, your second example will compile, too:

pub fn square_of_sum(n: u32) -> u32 {
    let num: u32 = (1..n + 1).collect::<Vec<_>>().iter().sum::<u32>().pow(2);
    num
}

Playground.


Note that a range is already an iterator, no need to collect it into a Vec first. So you can simplify your code into

pub fn square_of_sum(n: u32) -> u32 {
    (1..n + 1).sum::<u32>().pow(2)
}

Playground.

4 Likes

What do you mean? Neither of those work?

After cleaning it up this is my best guestimate what you want Rust Playground

1 Like