Skip to content

Type Inference not working when indexing with Into<usize> types #52921

@callym

Description

@callym

I have an enum Dim { X, Y, Z } that I've implemented Into<usize> for, so I can use it instead of 0, 1, 2, but I get type inference errors when using it. I've narrowed it down to this playground example.

If you change the last line to let c: i32 = a[i.into()]; then it gives an error about not knowing the type for i.into(), despite there only being one type that it can be?
I can use a[i as usize] which works fine for this case, but not sure why using .into() breaks things so badly.

enum I {
    X,
    Y,
    Z,
}

impl Into<usize> for I {
    fn into(self) -> usize {
        0
    }
}

fn main() {
    let a = vec![1i32, 2, 3];
    let i = I::X;
    let c = a[0];
    let c = a[i.into()];
}

(Playground)

Errors:

   Compiling playground v0.0.1 (file:///playground)
error[E0282]: type annotations needed
  --> src/main.rs:17:9
   |
17 |     let c = a[i.into()];
   |         ^
   |         |
   |         cannot infer type for `_`
   |         consider giving `c` a type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions