Cannot use what I imported

So I was trying to parse JSON using serde and I got this error as I tried to import Deserialize to statically parse JSON. Here is the file, it is very small:

use serde::Deserialize; // Says this import isn't used

#[derive(Deserialize)] // Tells me it can't derive this macro in this scope
pub struct Config {
  java_home: String,
  output_dir: String,
  mods: (String, [String; 2]),
}

I checked this isn't a stupid IDE error its the same error with cargo run too

I literally basically copied the example code from serde_json - Rust Docs

Have you enabled the "derive" feature of the serde crate on your Cargo.toml?

https://serde.rs/derive.html

I have not. I enabled it and it works now so thanks a lot! Btw, it doesn't tell me anywhere that I have to enable the feature, is it common knowledge or am I just blind?

It can be found in Serde documentation. Quoting docs for Deserialize:

Additionally, Serde provides a procedural macro called serde_derive to automatically generate Deserialize implementations for structs and enums in your program. See the derive section of the manual for how to use this.

The link here leads to the page already linked above by hyeonu, where we see:

Add serde = { version = "1.0", features = ["derive"] } as a dependency in Cargo.toml.

For what is worth, I consider this a diagnostic bug. The reason it behaves this way is because the way rustc handles cfg! feature flags is that everything behind an "off" feature flag is pretty much invisible to the stages after parsing of the compiler. In order for the compiler to understand what happened here, it would need to actually try to compile every "branch" of feature flags and collect and keep that information around to provide appropriate suggestions when something would have worked, had the feature flag been on.

3 Likes

In this particular case there is no way for rustc to know that serde_derive::Deserialize is a proc macro and not a type or trait. Cargo doesn't compile serde_derive if the derive feature flag is not set. In fact rustc doesn't even know that there is a Deserialize imported from serde_derive. Serde uses use serde_derive::*;

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.