Reputation: 3401
I can't seem to get the provided example of serializing a struct with serde to work. I'm implementing the trait Serialize
for my Address
struct, but I get a compile error that this trait is not implemented. What am I doing wrong?
[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`
Upvotes: 1
Views: 2261
Reputation: 2146
You need to specify the derive
feature for serde
in Cargo.toml
.
serde = { version = "1.0.118", features = ["derive"] }
See this for more info: https://serde.rs/derive.html
Upvotes: 4