Serialization/Deserialization : cannot find derive macro

I'm testing Serialize/Deserialize with the code below given by Google Bard, but I'm always getting this error:

error: cannot find derive macro `Serialize` in this scope
 --> src/main.rs:3:10
  |
3 | #[derive(Serialize, Deserialize)]

What's wrong with my code ?

use serde::Deserialize;
use serde::Serialize;

#[derive(Debug, Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let person = Person {
        name: "John Doe".to_string(),
        age: 30,
    };

    let serialized_person = serde_json::to_string(&person).unwrap();

    println!("Serialized person: {}", serialized_person);

    let deserialized_person: Person = serde_json::from_str(&serialized_person).unwrap();

    println!("Deserialized person: {:?}", deserialized_person);
}

Cargo.toml:

[package]
name = "serialization"
version = "0.1.0"
edition = "2021"

[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }

Your code works fine.

The error occurs when features = ["derive"] is not enabled. In your snippet, it exists thus works.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.