rust - Slice to fixed-size array -


this question has answer here:

i have structure fixed-sized arrays:

struct publicheaderblock_las14 {     file_signature: [u8; 4],     file_source_id: u16,     global_encoding: u16,     project_id_data_1: u32,     project_id_data_2: u16,     project_id_data_3: u16,     project_id_data_4: [u8; 8],     version_major: u8,     version_minor: u8,     systemidentifier: [u8; 32], // ... } 

i'm reading in bytes file fixed size array , copying bytes struct bit bit.

fn create_header_struct_las14(&self, buff: &[u8; 373]) -> publicheaderblock_las14 {     publicheaderblock_las14 {         file_signature: [buff[0], buff[1], buff[2], buff[3]],         file_source_id: (buff[4] | buff[5] << 7) u16,         global_encoding: (buff[6] | buff[7] << 7) u16,         project_id_data_1: (buff[8] | buff[9] << 7 | buff[10] << 7 | buff[11] << 7) u32,         project_id_data_2: (buff[12] | buff[13] << 7) u16,         project_id_data_3: (buff[14] | buff[15] << 7) u16,         project_id_data_4: [buff[16], buff[17], buff[18], buff[19], buff[20], buff[21], buff[22], buff[23]],         version_major: buff[24],         version_minor: buff[25],         systemidentifier: buff[26..58]     } } 

the last line (systemidentifier) doesn't work, because in struct [u8; 32] , buff[26..58] slice. can return convert slice fixed sized array on range, instead of doing i've done file_signature?

there no safe way initialize array in struct slice. need either resort unsafe block operates directly on uninitialized memory, or use 1 of following 2 initialize-then-mutate strategies:

construct desired array, use initialize struct.

struct foo {     arr: [u8; 32], }  fn fill(s: &[u8; 373]) -> foo {     let mut a: [u8; 32] = default::default();     a.copy_from_slice(&s[26..58]);     foo { arr: } } 

or initialize struct, mutate array inside struct.

#[derive(default)] struct foo {     arr: [u8; 32], }  fn fill(s: &[u8; 373]) -> foo {     let mut f: foo = default::default();     f.arr.copy_from_slice(&s[26..58]);     f } 

the first 1 cleaner if struct has many members. second 1 may little faster if compiler cannot optimize out intermediate copy. use unsafe method if performance bottleneck of program.