How come I don't need to use Debug in a derive?

This example compiles and runs fine:

#[derive(Debug)]
struct Foo {
}

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

But Debug isn't in the Rust prelude. So how come it doesn't need a use statement?

If derive was completely magic, it would make more sense, but you can make your own traits derive-able, so I'd expect it to actually really check the parameter. I mean, what if I had my own trait called Debug that could also be derived? :slight_smile:

Yes, some derives like Debug are built in to the compiler itself, but it's not the reason here. It's that the trait Debug and the derive Debug is not the same thing. They even have separate document.

For another example, serde::Serialize is popular 3rd party trait with custom derive. At the root of the serde crate the trait Serialize is exported here, and the derive is exported here. Since they have same name use serde::Serialize; imports both at once.

6 Likes

And the macro is, in fact, reexported within the prelude. You can notice that for some traits, like Eq, both the trait and the corresponding macro are here, and for some, like Debug, - the macro only.

3 Likes

Thanks, both! Very interesting!

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.