问题
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?
回答1:
#[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.
回答2:
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 createT
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
来源:https://stackoverflow.com/questions/29233324/can-we-automatically-derive-a-user-defined-trait