Search code examples
rustserderust-macros

Why Am I Getting "Cannot Derive Macro In This Scope"?


Attempting cargo build against this code:

#![allow(unused)]

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

#[derive(Serialize, Deserialize,Debug)]
struct Repository{
    r#type: String,
    url: String,
}

fn main() {
    println!("Hello, world!");
}

And here's the cargo.toml file:

[package]
name = "demo_err"
version = "0.1.0"
authors = ["Onorio Catenacci <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = "1.0.104"
serde_json = "1.0.44"

Of course my real code is a bit larger but that's the smallest bit of code with which I can reproduce the error.

I get the following errors:

   Compiling demo_err v0.1.0 (U:\skunkworks\rust\demo_err)
error: cannot find derive macro `Serialize` in this scope
 --> src\main.rs:9:10
  |
9 | #[derive(Serialize, Deserialize,Debug)]
  |          ^^^^^^^^^

error: cannot find derive macro `Deserialize` in this scope
 --> src\main.rs:9:21
  |
9 | #[derive(Serialize, Deserialize,Debug)]
  |                     ^^^^^^^^^^^

Now I would assume I've done something wrong--except for this sample code from serde_json. It's like this:

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

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

Now, one obvious difference is the r#type but using a different name doesn't fix the error. Another obvious difference is serde_json::{Result, Value} but removing Value doesn't fix the error either.

Obviously something is different between my code and that sample but for the life of me I cannot figure out what's different. Can someone please point me in the right direction?


EDIT:

Yes I am aware of another question that is solved by the same required feature. However the error message presented in this case is not the same as the error presented in the other case. I wouldn't expect someone to be able to translate the two different error scenarios into the same solution. Please leave this open.

Specifically this:

error: cannot find derive macro Serialize in this scope

which is the main thing I'm asking about vs. this

warning: unused imports: Deserialize, Serialize

Which is the main point of the other question.


Solution

  • You need to activate the required feature to use derive macros. You can do this by changing serde declaration in cargo.toml :

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

    or via cargo command:

    cargo add serde --features derive
    

    For more information please follow: https://serde.rs/derive.html

    See also :