]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/attribute.md
New upstream version 1.76.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / attribute.md
CommitLineData
2c00a5a8
XL
1# Attributes
2
3An attribute is metadata applied to some module, crate or item. This metadata
4can be used to/for:
5
6<!-- TODO: Link these to their respective examples -->
7
8* [conditional compilation of code][cfg]
9* [set crate name, version and type (binary or library)][crate]
10* disable [lints][lint] (warnings)
11* enable compiler features (macros, glob imports, etc.)
12* link to a foreign library
13* mark functions as unit tests
14* mark functions that will be part of a benchmark
064997fb 15* [attribute like macros][macros]
2c00a5a8 16
ed00b5ec
FG
17Attributes look like `#[outer_attribute]` or `#![inner_attribute]`,
18with the difference between them being where they apply.
19
20- `#[outer_attribute]` applies to the [item][item] immediately
21 following it. Some examples of items are: a function, a module
22 declaration, a constant, a structure, an enum. Here is an example
23 where attribute `#[derive(Debug)]` applies to the struct
24 `Rectangle`:
25 ```rust
26 #[derive(Debug)]
27 struct Rectangle {
28 width: u32,
29 height: u32,
30 }
31 ```
32
33- `#![inner_attribute]` applies to the enclosing [item][item] (typically a
4b012472 34 module or a crate). In other words, this attribute is interpreted as
ed00b5ec
FG
35 applying to the entire scope in which it's place. Here is an example
36 where `#![allow(unusude_variables)]` applies to the whole crate (if
37 placed in `main.rs`):
38 ```rust
39 #![allow(unused_variables)]
40
41 fn main() {
42 let x = 3; // This would normally warn about an unused variable.
43 }
44 ```
2c00a5a8
XL
45
46Attributes can take arguments with different syntaxes:
47
48* `#[attribute = "value"]`
49* `#[attribute(key = "value")]`
50* `#[attribute(value)]`
51
52Attributes can have multiple values and can be separated over multiple lines, too:
53
54```rust,ignore
55#[attribute(value, value2)]
56
57
58#[attribute(value, value2, value3,
59 value4, value5)]
60```
61
dc9dc135
XL
62[cfg]: attribute/cfg.md
63[crate]: attribute/crate.md
ed00b5ec 64[item]: https://doc.rust-lang.org/stable/reference/items.html
2c00a5a8 65[lint]: https://en.wikipedia.org/wiki/Lint_%28software%29
064997fb 66[macros]: https://doc.rust-lang.org/book/ch19-06-macros.html#attribute-like-macros