无法使 Serde Serialize 工作的基本示例

Can't make basic example of Serde Serialize work

Serde 文档说:

All of these can be serialized using Serde out of the box.

serde_json is just for the example, not required in general.

这正是我所需要的,将结构基本序列化为某种基本二进制格式。我不需要 JSON 格式,我想保持简单以便能够将结构存储在文件中或将其发送到网络。该文档不清楚如何使用 serde 进行基本(二进制或默认)序列化,它只显示带有 JSON 的示例,但这不是我要找的。我也不想实现自己的serialize方法,我想使用Serde提供的默认方法。

这是我的例子,我该如何让它发挥作用?

use serde::{Serialize, Deserialize,Serializer};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    //let serialized = serde::serialize(&point).unwrap(); // <-- doesnt work!
    //let serialized = Serializer::serialize(&point); // <-- doesnt work!
    //let serialized = point.serialize(Serializer); // <-- doesn't work!
    println!("data = {:?}", serialized);
}

游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b57a77399280f19664bb004201319b32

这是我的依赖行:

[dependencies]
serde = { version = "1.0", features = ["derive"] }

如评论中所述,未提供 "default" 格式。

您必须选择所需的二进制格式并将其作为附加依赖项包含在内,就像您使用 serde_json.

一样

https://serde.rs/#data-formats. Of those serde_json is the only package hosted under https://github.com/serde-rs, all the binary formats are "third-party". Cross-referencing it with the list of crates tagged "serde" sorted by recent downloads, the CBOR crate 中有一个格式列表似乎很受欢迎。