Derive
derive
属性允许为数据结构自动生成新的项(item)。
它使用MetaListPaths语法来指定要实现的特性列表,或者指定要处理的derive 宏的路径。
例如,下面的代码将为 Foo
类型创建针对 PartialEq
和 Clone
特性的 impl
项。类型参数 T
将根据相应的 impl
被赋予 PartialEq
或 Clone
约束。
#![allow(unused)] fn main() { #[derive(PartialEq, Clone)] struct Foo<T> { a: i32, b: T, } }
生成的 PartialEq
的 impl
等价于
#![allow(unused)] fn main() { struct Foo<T> { a: i32, b: T } impl<T: PartialEq> PartialEq for Foo<T> { fn eq(&self, other: &Foo<T>) -> bool { self.a == other.a && self.b == other.b } } }
你可以通过过程宏为你自己的特性实现 derive
。
automatically_derived
属性
automatically_derived
属性会自动添加到通过 derive
属性为内置特性创建的实现(implementation)中。它没有直接作用,但可能被工具和诊断 lint 用于检测这些自动生成的实现。