【问题标题】:Implementing slice for custom type为自定义类型实现切片
【发布时间】:2023-03-29 18:50:02
【问题描述】:

我有这个结构:

struct Test {
    data: Vec<u8>,
}

impl Test {
    fn new() -> Self {
        return Test { data: Vec::new() };
    }
}

let a = Test::new();
// populate something into a...

我想为这种类型实现切片,例如&amp;a[2..5],它返回一个指向其内部data 的2..5 的切片。在 Rust 中可以做到这一点吗?

【问题讨论】:

    标签: rust


    【解决方案1】:

    您可以通过实现 Index 特征并将索引绑定到 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] } } ``
    • @MykMelez 我已经更新了我的代码。 SliceIndex 已经为 usize 实现。
    猜你喜欢
    • 2021-05-27
    • 2015-05-15
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多