2

I have a struct like this

#[derive(CustomTrait)]
struct Sample {
    v: Vec<u8>,
}

and my trait goes like this

trait CustomTrait {...}

Can I do the above stuff? It threw an error for me.

I want something similar to the Clone trait. Is this possible with Rust?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Shankar Us
  • 292
  • 1
  • 3
  • 18

2 Answers2

7

#[derive(Foo, Bar)] is sugar for #[derive_Foo] #[derive_Bar], so it is possible to implement your own decorator attribute in the same way as #[derive_Clone] is, but this requires you to write a compiler plugin, which is not a stable part of Rust and will not be stable in 1.0 (and will thus be unavailable in the stable and beta channels).

There is a little documentation on such matters in the book, but not much; you’re largely on your own with it.

Bear in mind that what you can actually do at that stage is limited; you have access to the struct definition only, and know nothing about the actual types mentioned. This is a good fit for all of the traits for which #[derive] support is built in, but is not for many other traits.

Ákos Vandra-Meyer
  • 1,890
  • 1
  • 23
  • 40
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
5

No, you can't. derive instructs the compiler to provide a basic implementation of the trait. You can't expect the compiler to magically know how to implement a user-defined trait.

You can only use derive with these traits (taken from http://rustbyexample.com/trait/derive.html):

  • Comparison traits: Eq, PartialEq, Ord, PartialOrd
  • Serialization: Encodable, Decodable
  • Clone, to create T from &T via a copy.
  • Hash, to compute a hash from &T.
  • Rand, to create a random instance of a data type.
  • Default, to create an empty instance of a data type.
  • Zero, to create a zero instance of a numeric data type.
  • FromPrimitive, to create an instance from a numeric primitive.
  • Debug, to format a value using the {:?} formatter.

NOTE: Apparently this was proposed and is being discussed here

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
  • I think `Copy` should be in this list. It is in the list in the linked document at rustbyexaple.com. – Lii Aug 13 '17 at 14:15
  • Just an update to this with Rust as it is now (for anybody that Googles this), you can derive custom stuff using procedural macros. The macro could be designed to read user-defined traits and do whatever. https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros – Kobato Sep 09 '22 at 13:30