Concatenate array slices

后端 未结 3 2202
失恋的感觉
失恋的感觉 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:48

    I'm afraid what you are asking is pretty much impossible if you require the result to be an actual slice. A slice is a view into a block of memory. Contiguous memory. If you want a new slice by combining two other slices you have to copy the contents to a new location, so that you get a new contiguous block of memory.

    If you are satisfied just concatenating by copying SliceConcatExt provides the methods concat and join on slices, which can be used on slices of custom types as long as they implement Clone:

    #[derive(Clone, PartialEq, Debug)]
    struct A {
        a: u64,
    }
    
    fn main() {
        assert_eq!(["hello", "world"].concat(), "helloworld");
        assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
        assert_eq!([[A { a: 1 }, A { a: 2 }], [A { a: 3 }, A { a: 4 }]].concat(),
                   [A { a: 1 }, A { a: 2 }, A { a: 3 }, A { a: 4 }]);
    }
    

    Note that even though SliceConcatExt is unstable, the methods themselves are stable. So there is no reason not to use them if copying is OK. If you can't copy you can't get a slice. In that case, you need to create a wrapper type, as explained in the answer of ker.

提交回复
热议问题