In Rust, I want to move all the elements out of a generic fixed-width array so I may then move them individually. The elements may but don't necessarily implement Copy
. I've come up with the following solution:
struct Vec3<T> {
underlying_array: [T; 3]
}
impl<T> Vec3<T> {
fn into_tuple(self) -> (T, T, T) {
let result = (
unsafe { mem::transmute_copy(&self.underlying_array[0]) },
unsafe { mem::transmute_copy(&self.underlying_array[1]) },
unsafe { mem::transmute_copy(&self.underlying_array[2]) },
);
mem::forget(self);
result
}
}
It seems to work, but I want to know if it's safe in the general case. Coming from C++, it's not generally safe to move objects by copying their bit patterns and bypassing the source object's destructor, which I think is essentially what I'm doing here. But in Rust, every type is movable (I think) and there's no way to customize move semantics (I think), so I can't think of any other way Rust would implement moving objects in the un-optimized case than a bitwise copy.
Is moving elements out of an array like this safe? Is there a more idiomatic way to do it? Is the Rust compiler smart enough to elide the actual bit copying transmute_copy
does when possible, and if not, is there a faster way to do this?
I think this is not a duplicate of How do I move values out of an array? because in that example, the array elements aren't generic and don't implement Drop
. The library in the accepted answer moves individual values out of the array one at a time while keeping the rest of the array usable. Since I want to move all the values at once and don't care about keeping the array, I think this case is different.