我有这个结构体:
struct Test {
data: Vec<u8>,
}
impl Test {
fn new() -> Self {
return Test { data: Vec::new() };
}
}
let a = Test::new();
// populate something into a...
我想为这个类型实现切片,比如执行 &a[2..5]
时,它返回一个指向其内部 data
的 2..5
的切片。在 Rust 中是否有可能做到这一点?
impl std::ops::Index for Test
{
type Output = u8;
fn index(&self, index: usize) -> &Self::Output {
&self.data[index]
}
}
- Myk MelezSliceIndex
已经为usize
实现了。 - Boiethios