Disclaimer: I am not very well versed in Rust at a low level, but I do not know what is considered “good practice” in the early stages of Rust. The recommendations given here may not be good ideas. I put them here, though ... well, they work.
You can transform them . The problem is that it will be a copy, the documentation says that this is the equivalent of calling memcpy
. This is not what you wanted, but it doesn’t matter here:
fn main() { let a: [[u8; 4]; 3] = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]; let b: [u8; 12] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; println!("a: {:?}", a); println!("b: {:?}", b); let c = unsafe { std::mem::transmute::<[[u8; 4]; 3], [u8; 12]>(a) }; println!("c: {:?}", c); }
Another option is to work with a raw pointer :
fn main() { let a: [[u8; 4]; 3] = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]; let b: [u8; 12] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; println!("a: {:?}", a); println!("b: {:?}", b); let c = &a as *const _ as *const [u8; 12];
which is also not particularly large.
The indicator may also be a pointer or a pointer to a variable the same type (as &mut T
can be discarded before *mut T
), and the above code works exactly the same way (with a
marked variability):
let c = &mut a as *mut [[u8; 4]; 3];
I really wonder if this is a bit of an XY issue. Maybe the way you work with your data can be changed so as not to require it?