派生

derive 属性 允许为数据结构自动生成新的条目

它使用MetaListPaths 语法来指定要实现的 trait 列表或要处理的派生宏的路径。

例如,以下代码将为 FooPartialEqClone trait 创建一个 impl 条目,类型参数 T 将被赋予适用于相应 implPartialEqClone 约束

#![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
    }
}
}

你可以通过过程宏为你自己的 trait 实现 derive

automatically_derived 属性

automatically_derived 属性 会自动添加到由内置 trait 的 derive 属性创建的实现中。它没有直接效果,但工具和诊断 lint 可能会使用它来检测这些自动生成的实现。