简体   繁体   中英

How to implement the `Index` trait for a 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]> .

Since you know you have a slice you only need to be generic over SliceIndex ask T to be Index and SliceIndex don't make sense. You want don't want implement Index<T> you want Index<Idx> . Idx being usize in your case.

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM