Skip to content

Misattribution of type inference location surrounding slice indices #156738

Description

@d0sboots

Code

fn main1() {
    let bad_idx = 0u8;
    let foo = [1, 2, 3][bad_idx.into()] as i32;
}

fn main2() {
    let bad_idx = 0u8;
    let foo = 0 + [1, 2, 3][bad_idx.into()];
}

fn main3() {
    let bad_idx = 0u8;
    let foo = [1, 2, 3][bad_idx.into()];
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0282]: type annotations needed
 --> src/lib.rs:3:15
  |
3 |     let foo = [1, 2, 3][bad_idx.into()] as i32;
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type

error[E0284]: type annotations needed
 --> src/lib.rs:8:17
  |
8 |     let foo = 0 + [1, 2, 3][bad_idx.into()];
  |                 ^ cannot infer type
  |
  = note: cannot satisfy `<i32 as Add<_>>::Output == _`

error[E0283]: type annotations needed
  --> src/lib.rs:13:33
   |
13 |     let foo = [1, 2, 3][bad_idx.into()];
   |                                 ^^^^
   |
   = note: cannot satisfy `_: From<u8>`
   = note: required for `u8` to implement `Into<_>`
help: try using a fully qualified path to specify the expected types
   |
13 -     let foo = [1, 2, 3][bad_idx.into()];
13 +     let foo = [1, 2, 3][<u8 as Into<T>>::into(bad_idx)];
   |

Some errors have detailed explanations: E0282, E0283, E0284.
For more information about an error, try `rustc --explain E0282`.
error: could not compile `playground` (lib) due to 3 previous errors

Desired output

For the first two functions, it should correctly identify the `into()` as the issue, instead of incorrectly highlighting a larger surrounding expression.

For the third, it's not even clear to me why it *doesn't* work. (`u8` does implement into for `usize`.) But, at least the problem location is clear, so I know what to fix.

Rationale and extra context

When I encountered this in the wild, it was more similar to the second form (with arithmetic), so the exact problem was very obscured. Trying to add explict casts (like the first form) didn't help.

Other cases

Rust Version

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=5a2136568a8f77eaaddd8190c4879464

Version listed is 1.97.0-nightly (2026-05-18 9eb3be26b46eccea1de7), I don't think I can run commandline stuff there

Anything else?

No response

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

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions