Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

派生

derive 属性 调用一个或多个派生宏,允许为数据结构自动生成新的程序项。你可以使用过程宏创建 derive 宏。

Example

PartialEq 派生宏为 Foo<T> where T: PartialEq 生成 PartialEq实现Clone 派生宏类似地为 Clone 生成实现。

#![allow(unused)]
fn main() {
#[derive(PartialEq, Clone)]
struct Foo<T> {
    a: i32,
    b: T,
}
}

生成的 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
    }
}

impl<T: Clone> Clone for Foo<T> {
    fn clone(&self) -> Self {
        Foo { a: self.a.clone(), b: self.b.clone() }
    }
}
}

derive 属性使用 MetaListPaths 语法来指定要调用的派生宏的路径列表。

derive 属性只能应用于结构体枚举联合体

derive 属性可以在一个项上使用任意次数。所有属性中列出的所有派生宏都会被调用。

derive 属性在标准库中导出为:

内置派生宏定义在语言预导入中。内置派生宏的列表如下:

内置派生宏在其生成的实现中包含 automatically_derived 属性

在宏展开期间,对于派生列表中的每个元素,相应的派生宏展开为零个或多个程序项

automatically_derived 属性

automatically_derived 属性 用于标注一个实现,以表明它是由派生宏自动创建的。它没有直接影响,但可以被工具和诊断 lint 用于检测这些自动生成的实现。

Example

给定 struct Example 上的 #[derive(Clone)]派生宏可能产生:

#![allow(unused)]
fn main() {
struct Example;
#[automatically_derived]
impl ::core::clone::Clone for Example {
    #[inline]
    fn clone(&self) -> Self {
        Example
    }
}
}

automatically_derived 属性使用 MetaWord 语法。

automatically_derived 属性只能应用于实现

Note

rustc 忽略其他位置的用法但会发出 lint 警告。这可能在将来成为错误。

在一个实现上多次使用 automatically_derived 的效果与使用一次相同。

Note

rustc 会对第一次之后的使用发出 lint 警告。

automatically_derived 属性没有行为。