Skip to content

[confusing error message] iterate over str #46216

Closed
@gnzlbg

Description

@gnzlbg

Given:

fn main() {
    for c in "foobarbaz" {
        println!("{}", c);
    }
}

Rust produces (playground):

error[E0277]: the trait bound `&str: std::iter::Iterator` is not satisfied
 --> src/main.rs:2:5
  |
2 | /     for c in "foobarbaz" {
3 | |         println!("{}", c);
4 | |     }
  | |_____^ `&str` is not an iterator; maybe try calling `.iter()` or a similar method
  |
  = help: the trait `std::iter::Iterator` is not implemented for `&str`
  = note: required by `std::iter::IntoIterator::into_iter`

The suggestion says iter or a similar method, but &str doesn't have an .iter() method (that's why it says "or a similar method").

I don't think this is good enough.

It should scan the methods of str that return something that implements Iterator (or can be auto-deref to something that implements it) and suggest those. In this case, chars(), bytes(),... The error message should look more like this:

error[E0277]: the trait bound `&str: std::iter::Iterator` is not satisfied
 --> src/main.rs:2:5
  |
2 | /     for c in "foobarbaz" {
3 | |         println!("{}", c);
4 | |     }
  | |_____^ `&str` is not an iterator
  |
  = help: the trait `std::iter::Iterator` is not implemented for `&str`
  = note: required by `std::iter::IntoIterator::into_iter`

The following methods of `&str` return an `Iterator`:
  - `chars`
  - `bytes`
  - ... 

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-resolveArea: Name/path resolution done by `rustc_resolve` specificallyC-enhancementCategory: An issue proposing an enhancement or a PR with one.WG-diagnosticsWorking group: Diagnostics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions