How to serialize primitive types in Rust?

What’s the proper way to use serde in order to serialize primitive types?
For example the following code snippet throws an error:

extern crate serde; // 1.0.137
use serde::Serialize;

fn main ()
{
    let test = true;
    let serialized: Vec<u8> = vec![];
    test.serialize(&mut serialized).unwrap();
    
}

And the error is:

error[E0277]: the trait bound &mut Vec<u8>: Serializer is not satisfied

How can I serialize any primitive type into a byte vector/slice in Rust using serde?

>Solution :

Serde provides two things for serialization: the Serialize trait and the Serializer trait. The Serialize trait is used to describe any value that can be serialized, like your test boolean, while the Serializer trait is used to define the data format used for serialization. This is why a call to serialize needs a Serializer: serde has no built in data formats.

One thing you could consider using is bincode, which has a convenient serialize function that constructs the bincode Serializer and creates a vec:

let serialized: Vec<u8> = bincode::serialize(test).unwrap();

Serde’s docs have a list of more data formats if you’re interested.

Leave a Reply