simgal
October 10, 2024, 8:43am
1
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
}
jofas
October 10, 2024, 8:56am
2
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
Ygg01
October 10, 2024, 8:57am
3
What do you mean? Neither of those work?
After cleaning it up this is my best guestimate what you want Rust Playground
1 Like
system
Closed
January 8, 2025, 8:57am
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.