Description
Here's some code (playground):
fn main() {
vec![(), ()].iter().sum::<i32>();
}
This has an obvious bug: You can't sum a bunch of ()
and get an i32
as a result. Here's the error message, though:
2 | vec![(), ()].iter().sum::<i32>();
| ^^^^^^^^^^^^^^^^^^^ --- required by a bound introduced by this call
| |
| the trait `Sum<&()>` is not implemented for `i32`
This was very confusing to me -- I'd expect to see an error saying something like Sum
not implemented for Iter<()>
. But instead it says that Sum
is not implemented for i32 But I'm not trying to sum i32s!
(my actual bug was actually that I'd accidentally added an extra ;
in my code, so that I was trying to sum ()
s instead of i32
, and the confusing error message made it harder to figure out that out)
What's actually going on here is:
i32
has a static method calledsum(iter: Iter<i32>)
, that comes from theSum
trait.Iter
has asum()
method that calls this static method oni32
- when I run
my_iter.sum()
, it tries to calli32::sum(my_iter)
i32::sum
isn't defined forIter<()>
- as a result, we get the error message
the trait
Sum<&()>is not implemented for
i32``
I might not have gotten all the types/terms exactly right, but I think that's the gist of it.
This all makes sense, but it's was pretty confusing for me to unwind. Maybe the compiler could have helped me unwind it?
reporting as requested by @estebank