2

I want to write a function which returns the square of a sum. My first shot looked like this:

fn square_of_sum(lim: u64) -> u64 {
    let sum: u64 = (1..lim).sum().pow(2);
    sum
}

Which gave me an error:

error[E0282]: type annotations needed
 --> src/lib.rs:2:20
  |
2 |     let sum: u64 = (1..lim).sum().pow(2);
  |                    ^^^^^^^^^^^^^^ cannot infer type for `S`
  |
  = note: type must be known at this point

So thinking rather C-ish, I explicitly cast the result of sum to u64, which still has an error

error[E0282]: type annotations needed
 --> src/lib.rs:2:20
  |
2 |     let sum: u64 = ((1..lim).sum() as u64).pow(2);
  |                    ^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `S`
  |
  = note: type must be known at this point

Isn't the result of sum on a Range<u64> a u64? Why is the type still missing after the use of as?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Paul Würtz
  • 1,641
  • 3
  • 22
  • 35
  • From the duplicate: *A type cast, such as that performed by `as`, requires converting from one type to another. You've specified the second type [...], but there's still no way for the compiler to deduce what the first type should be.* – Shepmaster Oct 08 '19 at 14:02
  • 3
    See also [Why can't Rust infer the resulting type of Iterator::sum?](https://stackoverflow.com/q/41017140/155423) for how to solve it. – Shepmaster Oct 08 '19 at 14:03
  • Thanks, so explicitly using the `sum` function of `u64` was necessary, like this `let sum_sqrt: u64 = (1u64..lim).sum::().pow(2);` – Paul Würtz Oct 08 '19 at 14:27
  • Yes, but pedantically it's not "the `sum` function of `u64`", it's providing a type parameter (`u64`) to the `sum` method of `Iterator`. Your entire function can just be `(1..lim).sum::().pow(2)`, no need for a variable, the variable type on `sum`, or the type on `1`. – Shepmaster Oct 08 '19 at 14:28

0 Answers0