gpt4 book ai didi

rust - 来自Struct示例的Serde JSON无法正常工作

转载 作者:行者123 更新时间:2023-12-03 11:42:27 25 4
gpt4 key购买 nike

我似乎无法获得提供的example来序列化带有Serde的结构才能正常工作。我正在为我的Serialize结构实现特征Address,但出现编译错误,指出该特征未实现。我究竟做错了什么?

[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`

最佳答案

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

serde = { version = "1.0.118", features = ["derive"] }
有关更多信息,请参见此: https://serde.rs/derive.html

关于rust - 来自Struct示例的Serde JSON无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65345581/

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