Skip to content

diagnostics: suggest dereferencing when trying to use a reference as index #96678

Closed
@matthiaskrgr

Description

@matthiaskrgr

Given the following code:

fn main() {
    let i: &usize = &1;
    let one_item_please: i32 = [1, 2, 3][i];
}

The current output is:

error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): the type `[{integer}]` cannot be indexed by `&usize`
--> src/main.rs:3:32 |
3 |     let one_item_please: i32 = [1, 2, 3][i];
  |                                ^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
  |
  = help: the trait `SliceIndex<[{integer}]>` is not implemented for `&usize`
  = note: required because of the requirements on the impl of `Index<&usize>` for `[{integer}]`

For more information about this error, try `rustc --explain E0277`.

Ideally the output should look like:
It would be great if rustc could suggest dereferencing: [i] -> [*i] which fixes the build

Metadata

Metadata

Assignees

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