结构示例中的 Serde JSON 不工作

Serde JSON from Struct Example Not Working

我似乎无法使用提供的 example 使用 serde 序列化结构。我正在为我的 Address 结构实现特性 Serialize,但是我得到一个编译错误,指出这个特性没有实现。我做错了什么?

[dependencies]
serde = "1.0.118"
serde_json = "1.0.60"
use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}
fn main(){
    print_an_address();
}

fn print_an_address() -> Result<()> {
    // Some data structure.
    let address = Address {
        street: "10 Downing Street".to_owned(),
        city: "London".to_owned(),
    };

    // Serialize it to a JSON string.
    let j = serde_json::to_string(&address)?;

    // Print, write to a file, or send to an HTTP server.
    println!("{}", j);

    Ok(())
}
error[E0277]: the trait bound `Address: Serialize` is not satisfied
    --> src\main.rs:21:35
     |
21   |     let j = serde_json::to_string(&address)?;
     |                                   ^^^^^^^^ the trait `Serialize` is not implemented for `Address`
     | 
    ::: C:\Users\Primary User\.cargo\registry\src\github.com-1ecc6299db9ec823\serde_json-1.0.60\src\ser.rs:2221:17
     |
2221 |     T: ?Sized + Serialize,
     |                 --------- required by this bound in `serde_json::to_string`

您需要在 Cargo.toml 中为 serde 指定 derive 功能。

serde = { version = "1.0.118", features = ["derive"] }

有关详细信息,请参阅此内容:https://serde.rs/derive.html