Rust: How to concatenate bytes together

Viewed 4359

I have already read the following link but still get some errors with my current attempt:

let data = &[37u8, 42u8];
let data_two = &[0x34u8, 0x32u8];
let res:Vec<u8> = [data, data_two].concat();

Also, ideally I would like to avoid concatenation, and write an array of u8 to a buffer, where I reserve the first two bytes for storing length and index like:

let nb:u8 = get_chunks_nb();
let index:u8 = get_chunk_index();
let header = &[nb, index];

// this kind of things in C:
memcpy(&buffer, header, 2);
memcpy(&buffer[2], chunk, chunk_len);

Thank you for your help!

1 Answers

I took a shot at it, but I'm not 100% sure as to why, I'm still new to Rust.

It looks like the compiler is seeing data and data_two as arrays, and so [data, data_two] is then an array of array and not an array of slice. Which is probably why it couldn't find the concat method on it.

By explicitely saying that data is a slice, everything seems to fall into place:

let data:&[u8] = &[37u8, 42u8];
let data_two = &[0x34u8, 0x32u8];
let mut res:Vec<u8> = [data, data_two].concat();
Related