为什么我得到“无法在此范围内派生宏”?

Ono*_*cci 2 rust serde rust-macros

尝试cargo build针对此代码:

#![allow(unused)]

use serde::{Deserialize, Serialize};
use serde_json::{Result, Value};

#[derive(Serialize, Deserialize,Debug)]
struct Repository{
    r#type: String,
    url: String,
}

fn main() {
    println!("Hello, world!");
}
Run Code Online (Sandbox Code Playgroud)

这是 cargo.toml 文件:

[package]
name = "demo_err"
version = "0.1.0"
authors = ["Onorio Catenacci <catenacci@ieee.org>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = "1.0.104"
serde_json = "1.0.44"
Run Code Online (Sandbox Code Playgroud)

当然,我的真实代码要大一些,但这是我可以重现错误的最小代码。

我收到以下错误:

   Compiling demo_err v0.1.0 (U:\skunkworks\rust\demo_err)
error: cannot find derive macro `Serialize` in this scope
 --> src\main.rs:9:10
  |
9 | #[derive(Serialize, Deserialize,Debug)]
  |          ^^^^^^^^^

error: cannot find derive macro `Deserialize` in this scope
 --> src\main.rs:9:21
  |
9 | #[derive(Serialize, Deserialize,Debug)]
  |                     ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

现在我假设我做错了什么——除了来自 serde_json 的这个示例代码。就像这样:

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)

现在,一个明显的区别是r#type使用不同的名称并不能修复错误。另一个明显的区别是serde_json::{Result, Value}但删除Value也不能修复错误。

显然我的代码和那个示例之间有些不同,但对于我的生活,我无法弄清楚有什么不同。有人可以指出我正确的方向吗?

Öme*_*den 6

您需要激活所需的功能才能使用派生宏。您可以通过更改serde声明来做到这一点cargo.toml

serde = { version = "1.0.104", features = ["derive"] }
Run Code Online (Sandbox Code Playgroud)

更多信息请关注:https : //serde.rs/derive.html

也可以看看 :