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 called sum(iter: Iter<i32>), that comes from the Sum trait.
Iter has a sum() method that calls this static method on i32
- when I run
my_iter.sum(), it tries to call i32::sum(my_iter)
i32::sum isn't defined for Iter<()>
- as a result, we get the error message
the trait Sum<&()>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
Here's some code (playground):
This has an obvious bug: You can't sum a bunch of
()and get ani32as a result. Here's the error message, though:This was very confusing to me -- I'd expect to see an error saying something like
Sumnot implemented forIter<()>. But instead it says thatSumis 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 ofi32, and the confusing error message made it harder to figure out that out)What's actually going on here is:
i32has a static method calledsum(iter: Iter<i32>), that comes from theSumtrait.Iterhas asum()method that calls this static method oni32my_iter.sum(), it tries to calli32::sum(my_iter)i32::sumisn't defined forIter<()>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