派生
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 属性在标准库中导出为:
内置派生在语言 prelude 中定义。内置派生的列表是:
内置派生在其生成的实现上包含 automatically_derived 属性。
在宏展开期间,对于派生列表中的每个元素,相应的派生宏展开为零个或多个项。
automatically_derived 属性
automatically_derived 属性 用于注释实现以指示它是由派生宏自动创建的。它没有直接影响,但工具和诊断 lint 可能使用它来检测这些自动生成的实现。
Example
给定
#[derive(Clone)]在struct Example上,派生宏可能产生:#![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 属性没有行为。