Problem implementing Index trait for simple struct

I'm trying to implement the Index trait for a simple trait, and I want to use it with usize. I added SliceIndex<[T], Output = T> so I can use T to index the slice inside A.

use std::ops::Index;
use std::slice::SliceIndex;

struct A <'a, T>{
    slice: &'a [T]
}

impl<'a, T: Index<T, Output = T> + SliceIndex<[T], Output = T>> Index<T>
    for A<'a, T>
{
    type Output = T;

    #[inline(always)]
    fn index(&self, index: T) -> &Self::Output {
        self.slice.index(index)
    }
}

fn main() {
    let mut aa: Vec<u64> = vec![0; 10];
    let coefficient_iterable = A{slice: &aa};
    println!("{}", coefficient_iterable[1usize]);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9564b39061cae3e19db14217c10b9d8a

But I get:

Error:

error[E0608]: cannot index into a value of type `A<'_, u64>`
  --> src/main.rs:22:20
   |
22 |     println!("{}", coefficient_iterable[1usize]);
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0608`.
error: could not compile `playground` due to previous error

I have no idea why, since usize implements SliceIndex<[T]>.

You're overloading T as the element type and the Index type and the container type. But you can't Index into a usize, say.

Playground.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.