You need to understand that arrays of different lengths are different data types. Just like i16 and i32 are different types, [u8; 2]
and [u8; 4]
are different types. Therefore packing both of them into an array (your first try) does not work, because all elements in an array have to be of the same type. Packing both of them into a Vector (your second try) also does not work, because every element in a vector has to be of the same type.
You therefore have three options:
- Pack them both together using a technique that allows packing variables of different data types together: Using a tuple or using a struct:
struct FileArray {
first: [u8; 4],
second: [u8; 2],
}
fn main() {
let file_struct = FileArray {
first: hex!("CFFAEDFE"),
second: hex!("4D5A"),
};
}
let file_tuple: ([u8; 4], [u8; 2]) = (hex!("CFFAEDFE"), hex!("4D5A"));
- Avoid having different dataypes: While
[u8; 2]
and [u8; 4]
are of diffent type, vectors of different size are of the same type and you can therefore pack two vectors of different length into the same array or vector.
let vec_1: Vec::<u8> = hex!("CFFAEDFE").to_vec();
let vec_2: Vec::<u8> = hex!("4D5A").to_vec();
let vec_ar: [Vec::<u8>; 2] = [vec_1, vec_2];
- Creating a datatype that can be both
[u8; 2]
or [u8; 4]
:
enum FileMagic {
Two([u8; 2]),
Four([u8; 4]),
}
fn main() {
let magic_ar: [FileMagic; 2] = [FileMagic::Four(hex!("CFFAEDFE")), FileMagic::Two(hex!("4D5A"))];
}
Note that the type annotations in my examples are optional.
Memory wise, those three solutions behave differently:
file_tuple stack-allocate 6 bytes (+padding).
vec_ar will stack-allocate 48 bytes (+padding) (a vec is a 24 byte stack allocation) and will heap allocate at least 4 bytes and will heap allocate at least another 2 bytes.
magic_ar will stack-allocate 10 bytes (+padding).