`-6ren"> `- 这个问题在这里已经有了答案: How do I fix "cannot find derive macro in this scope"? (1 个回答) 关闭 3 年前。 我想序列化一个结构,将它-6ren">
gpt4 book ai didi

rust - 版本 = "2018"使用或不使用 `extern crate `

转载 作者:行者123 更新时间:2023-11-29 07:58:29 28 4
gpt4 key购买 nike

<分区>

我想序列化一个结构,将它打印到标准输出,从另一个程序读取它并反序列化。我发现我可以使用 serde crate 和 Bincode作为数据格式。

我想到了这个例子:

#[macro_use]
extern crate serde;

use bincode::{deserialize, serialize};

#[derive(Serialize, Deserialize)]
struct Entity {
x: f32,
y: f32,
}

#[derive(Serialize, Deserialize)]
struct World(Vec<Entity>);

fn main() {
let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);

let encoded: Vec<u8> = serialize(&world).unwrap();
println!("{:?}", encoded);

let decoded: World = deserialize(&encoded[..]).unwrap();
}

Cargo.toml 我有:

[package]
name = "test"
version = "0.1.0"
edition = "2018"

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

但让我感到困惑的是,即使我已经声明使用 edition = "2018" 并且根据我的理解,这意味着 extern crate serde; 可能是省略,如果我删除行:

#[macro_use]
extern crate serde;

我收到多个错误,例如:

error: cannot find derive macro `Deserialize` in this scope
--> src/main.rs:3:21
|
3 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^

error: cannot find derive macro `Serialize` in this scope
--> src/main.rs:3:10
|
3 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^

error: cannot find derive macro `Deserialize` in this scope
--> src/main.rs:9:21
|
9 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^

error: cannot find derive macro `Serialize` in this scope
--> src/main.rs:9:10
|
9 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^

因此想知道何时或如何使用 edition = "2018"

#[macro_use] 的使用让我想起了 Python 中的装饰器,是否同样的逻辑适用于 Rust,或者正在进行更多的语言标准化工作,以便可能在 edition = "20XX 不需要 #[macro_use] 吗?

#[macro_use]
extern crate serde;

我正在使用 Rust 1.35.0。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com