[英]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]);
}
但我得到:
錯誤:
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
通用,要求T
是Index
而SliceIndex
沒有意義。 你不想實現Index<T>
你想要Index<Idx>
。 Idx
是usize
你的情況。
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.