]> git.proxmox.com Git - rustc.git/blob - src/doc/book/attributes.md
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / doc / book / attributes.md
1 % Attributes
2
3 Declarations can be annotated with ‘attributes’ in Rust. They look like this:
4
5 ```rust
6 #[test]
7 # fn foo() {}
8 ```
9
10 or like this:
11
12 ```rust
13 # mod foo {
14 #![test]
15 # }
16 ```
17
18 The difference between the two is the `!`, which changes what the attribute
19 applies to:
20
21 ```rust,ignore
22 #[foo]
23 struct Foo;
24
25 mod bar {
26 #![bar]
27 }
28 ```
29
30 The `#[foo]` attribute applies to the next item, which is the `struct`
31 declaration. The `#![bar]` attribute applies to the item enclosing it, which is
32 the `mod` declaration. Otherwise, they’re the same. Both change the meaning of
33 the item they’re attached to somehow.
34
35 For example, consider a function like this:
36
37 ```rust
38 #[test]
39 fn check() {
40 assert_eq!(2, 1 + 1);
41 }
42 ```
43
44 It is marked with `#[test]`. This means it’s special: when you run
45 [tests][tests], this function will execute. When you compile as usual, it won’t
46 even be included. This function is now a test function.
47
48 [tests]: testing.html
49
50 Attributes may also have additional data:
51
52 ```rust
53 #[inline(always)]
54 fn super_fast_fn() {
55 # }
56 ```
57
58 Or even keys and values:
59
60 ```rust
61 #[cfg(target_os = "macos")]
62 mod macos_only {
63 # }
64 ```
65
66 Rust attributes are used for a number of different things. There is a full list
67 of attributes [in the reference][reference]. Currently, you are not allowed to
68 create your own attributes, the Rust compiler defines them.
69
70 [reference]: ../reference.html#attributes