Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading