簡體   English   中英

如何為簡單結構實現`Index`特征?

[英]How to implement the `Index` trait for a simple struct?

我正在嘗試為一個簡單的特征實現Index特征,並且我想將它與usize一起使用。 我添加了SliceIndex<[T], Output = T>所以我可以使用T來索引A內的slice

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

但我得到:

錯誤:

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

我不知道為什么,因為usize實現了SliceIndex<[T]>

既然你知道你有一個切片,你只需要對SliceIndex通用,要求TIndexSliceIndex沒有意義。 你不想實現Index<T>你想要Index<Idx> Idxusize你的情況。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM