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
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.