属性

属性是应用于某些模块、crate 或项目的元数据。这些元数据可以用于:

属性看起来像 #[outer_attribute]#![inner_attribute],它们之间的区别在于它们的应用位置。

  • #[outer_attribute] 应用于紧随其后的。项的一些示例包括:函数、模块声明、常量、结构体、枚举。这里有一个示例,其中属性 #[derive(Debug)] 应用于结构体 Rectangle

    #![allow(unused)]
    fn main() {
    #[derive(Debug)]
    struct Rectangle {
        width: u32,
        height: u32,
    }
    }
  • #![inner_attribute] 应用于封闭的(通常是模块或 crate)。换句话说,此属性被解释为应用于其放置的整个作用域。这里有一个示例,其中 #![allow(unused_variables)] 应用于整个 crate(如果放置在 main.rs 中)

    #![allow(unused_variables)]
    
    fn main() {
        let x = 3; // This would normally warn about an unused variable.
    }

属性可以接受具有不同语法的参数

  • #[attribute = "value"]
  • #[attribute(key = "value")]
  • #[attribute(value)]

属性可以有多个值,也可以在多行中分隔

#[attribute(value, value2)]


#[attribute(value, value2, value3,
            value4, value5)]