Custom Derive

Minimum Rust version: 1.15

In Rust, you’ve always been able to automatically implement some traitsthrough the derive attribute:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. #[derive(Debug)]
  4. struct Pet {
  5. name: String,
  6. }
  7. }

The Debug trait is then implemented for Pet, with vastly less boilerplate. For example, without derive, you'd haveto write this:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. use std::fmt;
  4. struct Pet {
  5. name: String,
  6. }
  7. impl fmt::Debug for Pet {
  8. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  9. match self {
  10. Pet { name } => {
  11. let mut debug_trait_builder = f.debug_struct("Pet");
  12. let _ = debug_trait_builder.field("name", name);
  13. debug_trait_builder.finish()
  14. }
  15. }
  16. }
  17. }
  18. }

Whew!

However, this only worked for traits provided as part of the standardlibrary; it was not customizable. But now, you can tell Rust what to do whensomeone wants to derive your trait. This is used heavily in popular crateslike serde and Diesel.

For more, including learning how to build your own custom derive, see TheRust ProgrammingLanguage.