Skip to content

Suggest to use .chars().nth(x) or .as_bytes() when trying to index str #57055

Closed
@ariasuni

Description

@ariasuni

It’s a pain point for beginners that they cannot index Strings or strs. It would make it much less frustrating if they got an helpful error message.

Right now, we get this error message:

error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> main.rs:2:18
  |
2 |     let _value = "test"[0];
  |                  ^^^^^^^^^ `str` cannot be indexed by `{integer}`
  |
  = help: the trait `std::ops::Index<{integer}>` is not implemented for `str`

But it’s not clear what we should do, and the error message doesn’t guide the user toward the solution. It would be better if there was an error message as the following instead:

error[EXXXX]: cannot index `String` or string slice (`str`)
 --> main.rs:2:24
  |
  |     let _value = "test"[0];
  |                        ^^^ cannot index here
  |
  |
  = help: consider using `.chars()` or `.to_bytes()`

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.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions