- 
                Notifications
    You must be signed in to change notification settings 
- Fork 13.9k
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:
- i32has a static method called- sum(iter: Iter<i32>), that comes from the- Sumtrait.
- Iterhas a- sum()method that calls this static method on- i32
- when I run my_iter.sum(), it tries to calli32::sum(my_iter)
- i32::sumisn't defined for- Iter<()>
- as a result, we get the error message the traitSum<&()>is not implemented fori32``
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