Skip to content

Implementation of Index<Foo> prevents indexing arrays by other index types #35873

Open
@ghost

Description

use std::ops::Index;

enum Foo {
    Zero,
    One,
    Two,
}

impl Index<Foo> for [u8; 3] {
    type Output = u8;

    fn index(&self, index: Foo) -> &u8 {
        unsafe { self.get_unchecked(index as usize) }
    }
}

fn main() {
    let arr: [u8; 3] = [0, 1, 2];

    // OK:
    let _ = arr[Foo::Two];

    // Error:
    let _ = arr[2usize];
    //          ^^^^^^ expected enum `Foo`, found `usize`

    // Error:
    let _ = &arr[0usize..2];
    //           ^^^^^^^^^ expected enum `Foo`, found struct `std::ops::Range<usize>`

    // Error:
    let _ = &arr[..];
    //           ^^ expected enum `Foo`, found struct `std::ops::RangeFull`
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-arrayArea: `[T; N]`A-type-systemArea: Type systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types 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