Implementing generic container over Index


#1

I’m struggling to implement a container that may contain anything which implements Index. The main hurdle is, that &[T] does not implement Index. Thus one can’t put a &[T] into it. I came up with this snippet. It seems to be overly complicated:
use std::ops::{Deref, Index};

struct Container<T, K: Index<usize> + ?Sized> where T: Deref<Target=K> {
    data: T
}

impl<T, K: Index<usize> + ?Sized> Container<T, K> where T: Deref<Target=K> {
    fn idx(&self, idx: usize) -> &<K as Index<usize>>::Output {
        &self.data[idx]
    }
}

fn main() {
    let foo: Container<Vec<u8>, _> = Container { data: vec![0; 10] };
    println!("foo[0] = {}", foo.idx(0));
    let bar: Container<&[u8], _> = Container { data: &[1; 10][..] };
    println!("bar[0] = {}", bar.idx(0));

}

Unfortunately I can’t simply do

use std::ops::{Deref, Index};

struct Container<T> where T: Deref<Target=Index<usize>> {
    data: T
}
impl<T> Container<T> where T: Deref<Target=Index<usize>> {
    fn idx(&self, idx: usize) -> &<<T as Deref>::Target as Index<usize>>::Output {
        &self.data[idx]
    }
}


fn main() {
    let bar: Container<&[u8]>;
}

since this doesn’t compile. Am I overlooking something or is it really that difficult?