error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
--> src/main.rs:2:5
|
2 | std::mem::swap(a, b);
| ^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[u8]`
note: required by a bound in `std::mem::swap`
But as far as i know/believe, references to slices are Sized.
Any tips?
In your call, T is therefore [u8] and not &mut [u8], which is not Sized. In general, each [u8] represents a fixed portion of memory with an unknown (at compile-time) length. If a and b have different lengths, swapping them would be impossible, as the larger one won't fit inside the space of the smaller.
You can write something like this, which will swap the first n items, where n is the length of the shorter slice:
pub fn swap_slice_u8(a: &mut [u8], b: &mut [u8]) {
for (a_n, b_n) in a.iter_mut().zip(b.iter_mut()) {
std::mem::swap(a_n, b_n);
}
}
There’s also <[T]>::swap_with_slice, which is likely more efficient than the swap_slice_u8 function in the first answer. If you want to support different-length slices the same way, you can limit both arguments to &mut foo[..n] where n = a.len().min(b.len()).