serde-rs / json

Strongly typed JSON library for Rust
Apache License 2.0
4.7k stars 536 forks source link

Example on "Creating JSON by serializing data structures" doesn't work. #1138

Closed tmp505 closed 1 month ago

tmp505 commented 1 month ago

Example:

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

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

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: `` cannot find derive macroSerialize` in this scope --> src/main.rs:4:10 4 #[derive(Serialize, Deserialize)] ^^^^^^^^^

note: Serialize is imported here, but it is only a trait, without a derive macro --> src/main.rs:1:26 | 1 | use serde::{Deserialize, Serialize}; | ^^^^^^^^^

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

note: Deserialize is imported here, but it is only a trait, without a derive macro --> src/main.rs:1:13 | 1 | use serde::{Deserialize, Serialize}; | ^^^^^^^^^^^

error[E0601]: main function not found in crate one --> src/main.rs:24:2 | 24 | } | ^ consider adding a main function to src/main.rs

error[E0277]: the trait bound Address: Serialize is not satisfied --> src/main.rs:18:35 18 let j = serde_json::to_string(&address)?; --------------------- ^^^^^^^^ the trait Serialize is not implemented for Address
required by a bound introduced by this call
 = help: the following other types implement trait `Serialize`:
           bool
           char
           isize
           i8
           i16
           i32
           i64
           i128
         and 131 others

note: required by a bound in serde_json::to_string --> /home/lum/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.117/src/ser.rs:2209:17 | 2207 | pub fn to_string(value: &T) -> Result | --------- required by a bound in this function 2208 | where 2209 | T: ?Sized + Serialize, | ^^^^^^^^^ required by this bound in to_string

Some errors have detailed explanations: E0277, E0601. For more information about an error, try rustc --explain E0277. error: could not compile one (bin "one") due to 4 previous errors