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;

    fn index(&self, index: T) -> &Self::Output {

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

But I get:


error[E0608]: cannot index into a value of type `A<'_, u64>`
  --> src/
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.


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.