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

属性

Syntax
InnerAttribute# ! [ Attr ]

OuterAttribute# [ Attr ]

Attr
      SimplePath AttrInput?
    | unsafe ( SimplePath AttrInput? )

AttrInput
      DelimTokenTree
    | = Expression

属性是一种通用的、自由格式的元数据,其解释取决于名称、约定、语言和编译器版本。属性的模型来自 ECMA-335 中的 Attributes,语法来自 ECMA-334(C#)。

内部属性,在井号 (#) 后写有感叹号 (!),应用于该属性声明所在的代码形式。

Example

#![allow(unused)]
fn main() {
// General metadata applied to the enclosing module or crate.
#![crate_type = "lib"]

// Inner attribute applies to the entire function.
fn some_unused_variables() {
  #![allow(unused_variables)]

  let x = ();
  let y = ();
  let z = ();
}
}

外部属性,在井号后没有感叹号,应用于该属性之后的代码形式。

Example

#![allow(unused)]
fn main() {
// A function marked as a unit test
#[test]
fn test_foo() {
    /* ... */
}

// A conditionally-compiled module
#[cfg(target_os = "linux")]
mod bar {
    /* ... */
}

// A lint attribute used to suppress a warning/error
#[allow(non_camel_case_types)]
type int8_t = i8;
}

属性由属性的路径组成,后跟一个可选的分隔 token 树,其解释由该属性定义。除宏属性之外的属性还允许输入为等号 (=) 后跟一个表达式。更多细节请参见下面的元项语法

属性可能是不安全的应用。为了避免使用这些属性时出现未定义行为,必须满足编译器无法检查的某些义务。为了断言这些义务已被满足,属性被包裹在 unsafe(..) 中,例如 #[unsafe(no_mangle)]

以下属性是不安全的:

属性可以分为以下几类:

属性可以应用于语言中的多种形式:

元项属性语法

“元项“是大多数内置属性Attr 规则所使用的语法。它具有以下文法:

Syntax
MetaItem
      SimplePath
    | SimplePath = Expression
    | SimplePath ( MetaSeq? )

MetaSeq
    MetaItemInner ( , MetaItemInner )* ,?

MetaItemInner
      MetaItem
    | Expression

元项中的表达式必须可以宏展开为字面量表达式,并且不能包含整数或浮点类型后缀。非字面量表达式在语法上会被接受(并可以传递给过程宏),但在解析后会被拒绝。

注意,如果属性出现在另一个宏中,它将在那个外部宏展开后才展开。例如,以下代码将首先展开 Serialize 过程宏,该宏必须保留 include_str! 调用,以便其能被展开:

#[derive(Serialize)]
struct Foo {
    #[doc = include_str!("x.md")]
    x: u32
}

此外,属性中的宏只会在应用于该项的所有其他属性之后才展开:

#[macro_attr1] // 首先展开
#[doc = mac!()] // `mac!` 第四个展开。
#[macro_attr2] // 第二个展开
#[derive(MacroDerive1, MacroDerive2)] // 第三个展开
fn foo() {}

各种内置属性使用元项语法的不同子集来指定其输入。以下文法规则展示了一些常用形式:

Syntax
MetaWord
    IDENTIFIER

MetaNameValueStr
    IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL )

MetaListPaths
    IDENTIFIER ( ( SimplePath ( , SimplePath )* ,? )? )

MetaListIdents
    IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER )* ,? )? )

MetaListNameValueStr
    IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr )* ,? )? )

元项的一些示例:

风格示例
MetaWordno_std
MetaNameValueStrdoc = "example"
MetaListPathsallow(unused, clippy::inline_always)
MetaListIdentsmacro_use(foo, bar)
MetaListNameValueStrlink(name = "CoreFoundation", kind = "framework")

活跃属性与惰性属性

属性要么是活跃的,要么是惰性的。在属性处理期间,活跃属性会从其所附着的代码形式中移除自身,而惰性属性会保留。

cfgcfg_attr 属性是活跃的。属性宏是活跃的。所有其他属性都是惰性的。

工具属性

编译器可以允许外部工具的属性,其中每个工具驻留在工具预导入中的自己的模块中。属性路径的第一个段是工具的名称,可以有一个或多个额外的段,其解释由工具决定。

当工具未被使用时,该工具的属性会在没有警告的情况下被接受。当工具被使用时,由该工具负责处理和解释其属性。

如果使用了 no_implicit_prelude 属性,则工具属性不可用。

#![allow(unused)]
fn main() {
// 告诉 rustfmt 工具不要格式化后面的元素。
#[rustfmt::skip]
struct S {
}

// 控制 clippy 工具的"圈复杂度"阈值。
#[clippy::cyclomatic_complexity = "100"]
pub fn f() {}
}

Note

rustc 目前识别工具 “clippy”、“rustfmt”、“diagnostic”、“miri” 和 “rust_analyzer”。

内置属性索引

以下是所有内置属性的索引。

  • 条件编译

    • cfg — 控制条件编译。
    • cfg_attr — 有条件地包含属性。
  • 测试

    • test — 将函数标记为测试。
    • ignore — 禁用一个测试函数。
    • should_panic — 指示测试应产生 panic。
  • 派生

  • 诊断

  • ABI、链接、符号和 FFI

    • link — 指定与 extern 块链接的原生库。
    • link_name — 指定 extern 块中函数或静态变量的符号名称。
    • link_ordinal — 指定 extern 块中函数或静态变量的符号序号。
    • no_link — 阻止链接外部 crate。
    • repr — 控制类型布局。
    • crate_type — 指定 crate 类型(库、可执行文件等)。
    • no_main — 禁用生成 main 符号。
    • export_name — 指定函数或静态变量的导出符号名称。
    • link_section — 指定函数或静态变量使用的目标文件段。
    • no_mangle — 禁用符号名称修饰。
    • used — 强制编译器在输出目标文件中保留静态项。
    • crate_name — 指定 crate 名称。
  • 代码生成

    • inline — 提示内联代码。
    • cold — 提示函数不太可能被调用。
    • naked — 阻止编译器生成函数序言和尾声。
    • no_builtins — 禁用某些内置函数的使用。
    • target_feature — 配置平台特定的代码生成。
    • track_caller — 将父调用位置传递给 std::panic::Location::caller()
    • instruction_set — 指定用于生成函数代码的指令集。
  • 文档

  • 预导入

  • 模块

    • path — 指定模块的文件名。
  • 限制

  • 运行时

  • 特性

    • feature — 用于启用不稳定或实验性的编译器特性。有关 rustc 中实现的特性,请参阅 The Unstable Book
  • 类型系统

    • non_exhaustive — 指示类型在未来会有更多字段/变体。
  • 调试器