Skip to content

Suggests changing slice-like type instead of index for invalid SliceIndex #139424

Open
@thaliaarchi

Description

@thaliaarchi

Following #138381, ByteStr now indexes with SliceIndex instead of Index/IndexMut. This worsened some diagnostics for indexing other types.

Since SliceIndex is “backwards”, this leads it to suggest other slice-like types (the LHS), instead of suggesting other index/range types which work for the LHS. When the LHS already indexes with SliceIndex, it's unhelpful to suggest other slice-like types. Furthermore, this leaks ByteStr into stable diagnostics (confirmed with either rust.channel = "stable" in bootstrap.toml or RUSTC_BOOTSTRAP=-1)

The affected diagnostics are shown in commit 9d379e1.

Code

fn main() {
    let x = vec![1];
    x[0i32]; //~ ERROR E0277
}

Current output

error[E0277]: the type `[{integer}]` cannot be indexed by `i32`
  --> tests/ui/indexing/index-help.rs:3:7
   |
LL |     x[0i32];
   |       ^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[{integer}]>` is not implemented for `i32`
   = help: the following other types implement trait `SliceIndex<T>`:
             `usize` implements `SliceIndex<ByteStr>`
             `usize` implements `SliceIndex<[T]>`
   = note: required for `Vec<{integer}>` to implement `Index<i32>`

Desired output

This was the output before that PR:

error[E0277]: the type `[{integer}]` cannot be indexed by `i32`
  --> tests/ui/indexing/index-help.rs:3:7
   |
LL |     x[0i32];
   |       ^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[{integer}]>` is not implemented for `i32`
           but it is implemented for `usize`
   = help: for that trait implementation, expected `usize`, found `i32`
   = note: required for `Vec<{integer}>` to implement `Index<i32>`

Rust Version

rustc 1.88.0 (56ffb4362 2025-04-05)
commit-hash: 56ffb43629bf58996c367073a0fa19e7d422df19
commit-date: 2025-04-05 10:18:03 +0200

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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