Skip to content

request: improve string indexing error message #56740

Closed
@steven807

Description

@steven807

The following buggy code:

fn f() {
    let s = "hello";
    let c = s[0];
}

produces the error:

error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> src/main.rs:3:13
  |
3 |     let c = s[0];
  |             ^^^^ `str` cannot be indexed by `{integer}`
  |
  = help: the trait `std::ops::Index<{integer}>` is not implemented for `str`

This is usefully documented in TRPL (ch08-02-strings), but that is not easily discoverable from the error. Meanwhile, the error itself is a natural one that programmers from many languages (C, C++, etc) might run into. Speaking as someone who spent some time assuming that the issue was related to slices/references/usize (i.e. various new, Rust-specific concepts), not strings and UTF-8 encoding, I wonder whether a special case might be produced, replacing error E0277, when the types involved are specifically strings/strs and integers.

Meta

rustc --version --verbose:

rustc 1.32.0-nightly (4a45578bc 2018-12-07)
binary: rustc
commit-hash: 4a45578bc58ff262864f72680cc02e83f5d2f5b3
commit-date: 2018-12-07
host: x86_64-apple-darwin
release: 1.32.0-nightly
LLVM version: 8.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-help-wantedCall for participation: Help is requested to fix this issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.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