attribute(属性)是应用于某些模块、crate 或item(项)的元数据。当属性作用于整个crate时,它们的语法为 #![crate_attribute],当它们用于模块或item时,语法为 #[item_attribute]。
属性可以接受参数,有以下几种语法形式:
- #[attribute = “value”]
- #[attribute(key = “value”)]
- #[attribute(value)]
属性可以存在多个值,而且多个值属性可以分开到多行中,如下:
#[attribute(value, value2)]
#[attribute(value, value2, value3,
value4, value5)]
使用属性,可以实现一些功能效果:
- 实现条件编译:#[cfg]属性。
- crate相关设置:#![crate_type]属性,设置crate类型;#![crate_name]属性,设置crate名称。
- lint检查:#[allow]属性消除编译相关警告;#[warn]属性对违反规则的编译进行警告,但继续编译;#[deny]属性对违反规则的情况会触发编译器报错;#[forbid]与#[deny]属性相同,但同时会禁止后面再更改 lint级别。
- #[test]属性标记函数作为单元测试。
…
以下是简单的代码样例:
#[cfg(test)] // 条件编译
mod tests {
#[test] // 单元测试函数
fn it_works() {}
}
// 这个 crate 是一个库文件
#![crate_type = "lib"]
// 库的名称为 “rary”
#![crate_name = "rary"]
pub fn public_function() {
println!("called rary's `public_function()`");
}
fn private_function() {
println!("called rary's `private_function()`");
}
pub fn indirect_access() {
print!("called rary's `indirect_access()`, that\n> ");
private_function();
}
fn used_function() {}
// `#[allow(dead_code)]` 属性可以禁用 `dead_code` lint
#[allow(dead_code)]
fn unused_function() {}
fn main() {
used_function();
}