keddad
keddad

Reputation: 1796

Rust says import is not used and can't find imported statements at the same time

I've got some structure I want to use Serde with. Like this one:

use serde::{Serialize, Deserialize};

#[derive(Serialize)]
struct GetLinkResponse {
    error: String,
    link: String,
}

But compiler says that:

  1. Serialize import is not used
  2. Serialize can't be found
error: cannot find derive macro `Serialize` in this scope
 --> src/structs.rs:3:10
  |
3 | #[derive(Serialize)]
  |          ^^^^^^^^^

warning: unused imports: `Deserialize`, `Serialize`
 --> src/structs.rs:1:13
  |
1 | use serde::{Serialize, Deserialize};
  |             ^^^^^^^^^  ^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

I guess I'm not understanding something about how use works. Can somebody explain me what is my mistake here?

Upvotes: 17

Views: 6955

Answers (1)

Boiethios
Boiethios

Reputation: 42739

You're victim of the "magic" behind automatic trait implementation, i.e. procedural macros. Usually, people give the procedural macro that implements a trait the same name as the trait (because it's convenient). Here, there is the trait serde::Serialize, but there is also the procedural macro that automatically implements that trait serde::Serialize.

They don't conflict because they live in difference namespaces, and the compiler infers from the context if it's a macro or a trait.

In your situation, you forgot to add the derive feature, so there is no proc macro in serde. Thus, you're importing a trait without using it, and you try to use a proc macro that doesn't exist.

The solution is to use the serde's derive feature:

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

or use the command line: cargo add serde -F derive

Upvotes: 38

Related Questions