Skip to content

Confusing error when summing iterator of () #105184

Closed
@jvns

Description

@jvns

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemD-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions