What is difference between derive attribute and implementing traits for structures by yourself?

Viewed 335

I was wondering, what is difference between, for example #[derive(Debug)] attribute and implementing std::fmt::Debug trait for some struct by myself(or any other trait that can be added with derive attribute), assuming that my implementation is efficient? Will there be compile time difference? performance difference?

When should I use derive attribute and when should I implement traits by myself?

1 Answers

derive just provides a generally useful implementation of the trait (a default implementation which would often be what a user would want).

You should derive if the behaviour of derive is what you're looking for, and that's it. It's a convenience for generally useful behaviour e.g. structural equality for (Partial)Eq, printing a literal-ish struct for Debug, etc… It doesn't make a difference when using the structure / trait.

A derive is just a special case of macro (custom derives are proc macros), so compilation would be infinitesimally slower: rustc needs to run the proc macro first then compile its output. I doubt that makes any real difference though.

Related