19

The derive attribute allows certain traits to be automatically implemented for data structures. The reference gives the example:

#[derive(PartialEq, Clone)]
struct Foo<T> {
   a: i32,
   b: T
}

Is it possible to add your own derivable traits, or are these fixed by the compiler?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
andygavin
  • 2,784
  • 22
  • 32

2 Answers2

18

A small number of derivable traits are hard-coded in the compiler.

Rust 1.15 stabilized procedural macros which allow for the creation of custom derive attributes. If you need to support stable versions of Rust before 1.15, there is a crate that uses macro hackery to derive custom traits.

Mingwei Samuel
  • 2,917
  • 1
  • 30
  • 40
fjh
  • 12,121
  • 4
  • 46
  • 46
  • Thanks. Do you have an example of the crate macros? – andygavin Sep 17 '15 at 14:42
  • 1
    @andygavin No, sorry, I haven't actually used it yet. But [the docs](https://danielkeep.github.io/rust-custom-derive/doc/custom_derive/index.html) have an example. – fjh Sep 17 '15 at 19:54
10

The release of Rust 1.15 allows custom traits to be derived. They easiest way to do this is by using the syn and quote crates.

JelteF
  • 3,021
  • 2
  • 27
  • 35