简体   繁体   English

如何在 Rust 中序列化原始类型?

[英]How to serialize primitive types in Rust?

What's the proper way to use serde in order to serialize primitive types?使用serde序列化原始类型的正确方法是什么? 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错误[E0277]: 特征绑定&mut Vec<u8>: Serializer程序

How can I serialize any primitive type into a byte vector/slice in Rust using serde ?如何使用serde将任何原始类型序列化为 Rust 中的字节向量/切片?

Serde provides two things for serialization: the Serialize trait and the Serializer trait. Serde 为序列化提供了两件事: Serialize trait 和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. Serialize trait 用于描述任何可以序列化的值,例如test布尔值,而Serializer trait 用于定义用于序列化的数据格式。 This is why a call to serialize needs a Serializer : serde has no built in data formats.这就是为什么调用serialize需要一个Serializer器:serde 没有内置的数据格式。

One thing you could consider using is bincode , which has a convenient serialize function that constructs the bincode Serializer and creates a vec:您可以考虑使用的一件事是bincode ,它有一个方便的serialize函数,可以构造 bincode Serializer并创建一个 vec:

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

Serde's docs have a list of more data formats if you're interested.如果您有兴趣,Serde 的文档会列出更多数据格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM