官术网_书友最值得收藏!

  • Mastering Rust
  • Rahul Sharma Vesa Kaihlavirta
  • 283字
  • 2021-07-02 13:35:24

Attributes

An attribute is an annotation on an item in Rust code. Items are top-level language constructs in a crate such as functions, modules, structs, enums, and constant declarations, and other things that are meant to be defined only at the crate root. Attributes are usually compiler built-ins, but can also be created by users through compiler plugins. They instruct the compiler to inject extra code or meaning for the item that appears below them, or for the module if they apply to a module. We'll cover more on these in Chapter 7, Advanced Concepts. For the sake of keeping things in scope, we will talk about two forms of attributes here:

  • #[<name>]: This applies per item and usually appears above them in their definition. For example, test functions in Rust are annotated with the #[test] attribute. It signifies that the function is to be treated as part of the test harness.
  • #![<name>]: This applies to the whole crate. Notice that it has an extra ! there. It usually goes at the very top of your crate root.
If we are creating a library crate, the crate root is basically lib.rs, whereas when creating a binary crate, the crate root would be the main.rs file.

There are also other forms of attributes such as #[cfg(test)] that are used when writing tests within a module. This attribute is added on top of test modules to hint to the compiler to conditionally compile the module, but only when code is compiled in test mode. Attributes are not just limited to being used in testing code; they are widely used in Rust. We'll get to see more of them in upcoming chapters.

主站蜘蛛池模板: 永仁县| 宿州市| 黄梅县| 都安| 西和县| 仁布县| 罗定市| 友谊县| 东方市| 洛宁县| 凉城县| 聊城市| 灌云县| 革吉县| 阳高县| 南丹县| 北宁市| 孝昌县| 遵义县| 襄汾县| 武冈市| 通海县| 交口县| 天祝| 休宁县| 新泰市| 津市市| 荣成市| 仙居县| 郴州市| 东阳市| 克东县| 盐山县| 涞源县| 正镶白旗| 哈尔滨市| 五大连池市| 东辽县| 谷城县| 绍兴县| 明星|