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

例子

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 属性在标准库 预导入 中作为 core::prelude::v1::derive 导出。

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

内置派生在它们生成的 实现 上包含 automatically_derived 属性

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

automatically_derived 属性

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

例子

给定 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 属性只能应用于 实现

注意

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

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

注意

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

automatically_derived 属性没有行为。