我们可以自动导出用户定义的特征吗? [英] Can we automatically derive a user-defined trait?
问题描述
我有一个这样的结构
#[derive(CustomTrait)]
struct Sample {
v: Vec<u8>,
}
我的性格是这样的
trait CustomTrait {...}
我可以做以上的事情吗?它为我抛出了一个错误.
Can I do the above stuff? It threw an error for me.
我想要类似于 Clone
特性的东西.这可以用 Rust 实现吗?
I want something similar to the Clone
trait. Is this possible with Rust?
推荐答案
#[derive(Foo, Bar)]
是 #[derive_Foo] #[derive_Bar]
,所以可以像 #[derive_Clone]
一样实现你自己的装饰器属性,但这需要你编写一个编译器插件,它不是 Rust 的稳定部分,将在 1.0 中不稳定(因此在稳定版和 Beta 版中不可用).
#[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.
请记住,您在那个阶段实际可以做的事情是有限的;您只能访问结构定义,并且对提到的实际类型一无所知.这非常适合内置 #[derive]
支持的所有特征,但不适用于许多其他特征.
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.
这篇关于我们可以自动导出用户定义的特征吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!