Can we automatically derive a user-defined trait? [duplicate]

不打扰是莪最后的温柔 提交于 2019-12-24 02:37:09

问题


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 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



来源:https://stackoverflow.com/questions/29233324/can-we-automatically-derive-a-user-defined-trait

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!