Home > Mobile >  Serialize a vector of serializable/serialized elements
Serialize a vector of serializable/serialized elements

Time:05-21

If we have a vector of serializable elements, how to serialize the vector?

In particular, how to process if each serialized element is a byte array (e.g [u8; 56])?

let mut byte_stream = data
    .iter()
    .map(|x| x.to_bytes())
    .collect::<Vec<_>>()

This snippet produces a variable of type Vec<[u8; 56]>.

To transmit data, I plan to use std::io::write but it requires a byte slice &[u8].

CodePudding user response:

You can create a Vec by flatten()ing it:

data.iter()
    .map(|x| x.to_bytes())
    .flatten()
    .collect::<Vec<_>>()

But if you immediately want to pass it into a writer, you don't need to collect it first. You can just loop over the iterator and write multiple times.

  • Related