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

af534d2
Opened by Deleted user at 2024-12-21 05:10:33
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 array: [u8; 3] = [0, 1, 2];

    // OK:
    let value = array[Foo::Two];

    // Error:
    let value = array[2];
    //                ^ expected enum `Foo`, found integer

    // Error:
    let slice: &[u8] = &array[0..2];
    //                        ^^^^ expected enum `Foo`, found struct `std::ops::Range`

    // Error:
    let slice: &[u8] = &array[..];
    //                        ^^ expected enum `Foo`, found struct `std::ops::RangeFull`
}
  1. 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`
    }
    

    Deleted user at 2020-01-31 04:49:38

  2. see also #24066

    Hanna Kruppe at 2016-08-21 15:58:23

  3. @rkruppe

    Different problem. Here you are looking for the <[u8] as Index<RangeFull>> impl, which is reachable only through an unsizing coercion. Because your impl matches, the unsizing is skipped.

    Ariel Ben-Yehuda at 2016-08-21 17:02:46

  4. Who's "me"? This issue isn't filed by me.

    But yes, it does seem to be a different cause on closer inspection, sorry for the noise.

    Hanna Kruppe at 2016-08-21 17:05:59