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

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.

主站蜘蛛池模板: 宝清县| 新平| 芦山县| 肇东市| 达州市| 宝清县| 白朗县| 石林| 泰宁县| 夏邑县| 马关县| 大英县| 儋州市| 宁明县| 古蔺县| 来安县| 沛县| 乌鲁木齐县| 苏尼特右旗| 竹北市| 凤山县| 郸城县| 吉木萨尔县| 龙陵县| 西宁市| 大连市| 长丰县| 孝感市| 靖安县| 上栗县| 永顺县| 东至县| 枣庄市| 牟定县| 伊吾县| 白玉县| 泾川县| 白河县| 旅游| 彭州市| 筠连县|