Skip to content

Misleading suggestion for missing trait bounds #40375

Open
@cuviper

Description

@cuviper

This is a simplified version of https://users.rust-lang.org/t/solved-iterator-filter-and-zip-in-place/9809/4

trait Foo {
    fn foo(self) -> Self;
}

impl<I, T, U> Foo for I
    where I: Iterator<Item = (T, U)>
{
    fn foo(self) -> Self {
        self
    }
}

fn main() {
    let v = vec![(1, 'a'), (2, 'b'), (3, 'c')];
    for x in v.iter().foo() {
        println!("{:?}", x);
    }
}

The error is:

error: no method named `foo` found for type `std::slice::Iter<'_, ({integer}, char)>` in the current scope
  --> <anon>:15:23
   |
15 |     for x in v.iter().foo() {
   |                       ^^^
   |
   = note: the method `foo` exists but the following trait bounds were not satisfied: `&std::slice::Iter<'_, ({integer}, char)> : std::iter::Iterator`
   = help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `foo`, perhaps you need to implement it:
   = help: candidate #1: `Foo`

The note: chose to report missing &Iter: Iterator, which is true, but it's not best thing it could have noted. I guess it's looking at &Iter because of some auto-ref in the method call. But if you force it to use Iter directly with UFCS, like Foo::foo(v.iter()), the note is more useful.

error[E0271]: type mismatch resolving `<std::slice::Iter<'_, ({integer}, char)> as std::iter::Iterator>::Item == (_, _)`
  --> <anon>:15:14
   |
15 |     for x in Foo::foo(v.iter()) {
   |              ^^^^^^^^ expected reference, found tuple
   |
   = note: expected type `&({integer}, char)`
              found type `(_, _)`
   = note: required because of the requirements on the impl of `Foo` for `std::slice::Iter<'_, ({integer}, char)>`
   = note: required by `Foo::foo`

So we do have an Iterator, just the wrong Item.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-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