为自定义类型实现切片功能

14

我有这个结构体:

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] 时,它返回一个指向其内部 data2..5 的切片。在 Rust 中是否有可能做到这一点?

1个回答

15

你可以通过实现Index trait,并将索引限制在SliceIndex中来实现。

struct Test {
    data: Vec<u8>,
}

impl Test {
    fn new(data: Vec<u8>) -> Self {
        Test { data }
    }
}

impl<Idx> std::ops::Index<Idx> for Test
where
    Idx: std::slice::SliceIndex<[u8]>,
{
    type Output = Idx::Output;

    fn index(&self, index: Idx) -> &Self::Output {
        &self.data[index]
    }
}

fn main() {
    let test = Test::new(vec![1, 2, 3]);

    let slice = &test[1..];
    assert_eq!(slice, [2, 3]);

    let first = &test[0];
    assert_eq!(first, &1);
}

如果您还想要一个返回u8的Index实现,添加如下impl会导致“Test的冲突实现”错误:impl std::ops::Index for Test { type Output = u8; fn index(&self, index: usize) -> &Self::Output { &self.data[index] } } - Myk Melez
@MykMelez 我已经更新了我的代码。SliceIndex 已经为 usize 实现了。 - Boiethios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接