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

属性(Attribute)是一种通用的、自由形式的元数据,根据名称、约定、语言和编译器版本进行解释。属性基于 ECMA-335 中的属性建模,语法来自 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;
}

属性由到属性的路径组成,后跟可选的分隔词法单元树,其解释由属性定义。除宏属性外,属性还允许输入为等号(=)后跟表达式。有关更多详细信息,请参阅下面的[元项语法][meta item syntax]。

属性可能是不安全的。为了避免使用这些属性时的未定义行为,必须满足编译器无法检查的某些义务。为了断言这些义务已满足,属性被包装在 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] // expanded first
#[doc = mac!()] // `mac!` is expanded fourth.
#[macro_attr2] // expanded second
#[derive(MacroDerive1, MacroDerive2)] // expanded third
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 属性是活动的。属性宏是活动的。所有其他属性都是惰性的。

工具属性

编译器可能允许外部工具的属性,每个工具位于工具 prelude中的自己的模块中。属性路径的第一段是工具的名称,有一个或多个额外段,其解释由工具决定。

当工具未使用时,工具的属性被接受而不发出警告。当工具正在使用时,工具负责处理和解释其属性。

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

#![allow(unused)]
fn main() {
// Tells the rustfmt tool to not format the following element.
#[rustfmt::skip]
struct S {
}

// Controls the "cyclomatic complexity" threshold for the clippy tool.
#[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 — 指定用于生成函数代码的指令集。
  • 文档

  • Prelude

  • 模块

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

  • 运行时

  • 功能

    • feature — 用于启用不稳定或实验性编译器功能。有关 rustc 中实现的功能,请参阅不稳定之书
  • 类型系统

    • non_exhaustive — 指示类型将来会添加更多字段/变体。
  • 调试器