Concatenate array slices

后端 未结 3 2157
失恋的感觉
失恋的感觉 2021-02-20 02:13

I have two (very large) arrays foo and bar of the same type. To be able to write some nice code, I would like to obtain a read-only slice, result

3条回答
  •  [愿得一人]
    2021-02-20 02:40

    For n arrays, you can implement it using a Vec like below:

    use std::ops::Index;
    
    struct VecSlice<'a, T: 'a>(Vec<&'a [T]>);
    
    impl<'a, T> Index for VecSlice<'a, T> {
        type Output = T;
        fn index(&self, mut index: usize) -> &T {
            for slice in self.0.iter() {
                if index < slice.len() {
                    return &slice[index];
                } else {
                    index -= slice.len();
                }
            }
            panic!("out of bound");
        }
    }
    

    And then access it like an array, just don't go out of bound.

    fn main() {
        let a1 = [0, 1, 2];
        let a2 = [7, 8, 9];
        let a = VecSlice(vec!(&a1, &a2));
        println!("{}", a[4]);
    }
    

    This prints out

    8
    

提交回复
热议问题