3 Any item declaration may have an _attribute_ applied to it. Attributes in Rust
4 are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
5 (C#). An attribute is a general, free-form metadatum that is interpreted
6 according to name, convention, and language and compiler version. Attributes
9 * A single identifier, the attribute name
10 * An identifier followed by the equals sign '=' and a literal, providing a
12 * An identifier followed by a parenthesized list of sub-attribute arguments
14 Attributes with a bang ("!") after the hash ("#") apply to the item that the
15 attribute is declared within. Attributes that do not have a bang after the hash
16 apply to the item that follows the attribute.
18 An example of attributes:
21 // General metadata applied to the enclosing module or crate.
22 #![crate_type = "lib"]
24 // A function marked as a unit test
30 // A conditionally-compiled module
31 #[cfg(target_os="linux")]
36 // A lint attribute used to suppress a warning/error
37 #[allow(non_camel_case_types)]
41 > **Note:** At some point in the future, the compiler will distinguish between
42 > language-reserved and user-available attributes. Until then, there is
43 > effectively no difference between an attribute handled by a loadable syntax
44 > extension and the compiler.
46 ## Crate-only attributes
48 - `crate_name` - specify the crate's crate name.
49 - `crate_type` - see [linkage](linkage.html).
50 - `feature` - see [compiler features](#compiler-features).
51 - `no_builtins` - disable optimizing certain code patterns to invocations of
52 library functions that are assumed to exist
53 - `no_main` - disable emitting the `main` symbol. Useful when some other
54 object being linked to defines `main`.
55 - `no_start` - disable linking to the `native` crate, which specifies the
56 "start" language item.
57 - `no_std` - disable linking to the `std` crate.
58 - `plugin` - load a list of named crates as compiler plugins, e.g.
59 `#![plugin(foo, bar)]`. Optional arguments for each plugin,
60 i.e. `#![plugin(foo(... args ...))]`, are provided to the plugin's
61 registrar function. The `plugin` feature gate is required to use
63 - `recursion_limit` - Sets the maximum depth for potentially
64 infinitely-recursive compile-time operations like
65 auto-dereference or macro expansion. The default is
66 `#![recursion_limit="64"]`.
67 - `windows_subsystem` - Indicates that when this crate is linked for a Windows
68 target it will configure the resulting binary's
69 [subsystem] via the linker. Valid values for this
70 attribute are `console` and `windows`, corresponding to
71 those two respective subsystems. More subsystems may be
72 allowed in the future, and this attribute is ignored on
75 [subsystem]: https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx
77 ### Module-only attributes
79 - `no_implicit_prelude` - disable injecting `use std::prelude::*` in this
81 - `path` - specifies the file to load the module from. `#[path="foo.rs"] mod
82 bar;` is equivalent to `mod bar { /* contents of foo.rs */ }`. The path is
83 taken relative to the directory that the current module is in.
85 ## Function-only attributes
87 - `main` - indicates that this function should be passed to the entry point,
88 rather than the function in the crate root named `main`.
89 - `plugin_registrar` - mark this function as the registration point for
90 [compiler plugins][plugin], such as loadable syntax extensions.
91 - `start` - indicates that this function should be used as the entry point,
92 overriding the "start" language item. See the "start" [language
93 item](#language-items) for more details.
94 - `test` - indicates that this function is a test function, to only be compiled
96 - `ignore` - indicates that this test function is disabled.
97 - `should_panic` - indicates that this test function should panic, inverting the success condition.
98 - `cold` - The function is unlikely to be executed, so optimize it (and calls
100 - `naked` - The function utilizes a custom ABI or custom inline ASM that requires
101 epilogue and prologue to be skipped.
103 ## Static-only attributes
105 - `thread_local` - on a `static mut`, this signals that the value of this
106 static may change depending on the current thread. The exact consequences of
107 this are implementation-defined.
111 On an `extern` block, the following attributes are interpreted:
113 - `link_args` - specify arguments to the linker, rather than just the library
114 name and type. This is feature gated and the exact behavior is
115 implementation-defined (due to variety of linker invocation syntax).
116 - `link` - indicate that a native library should be linked to for the
117 declarations in this block to be linked correctly. `link` supports an optional
118 `kind` key with three possible values: `dylib`, `static`, and `framework`. See
119 [external blocks](items.html#external-blocks) for more about external blocks. Two
120 examples: `#[link(name = "readline")]` and
121 `#[link(name = "CoreFoundation", kind = "framework")]`.
122 - `linked_from` - indicates what native library this block of FFI items is
123 coming from. This attribute is of the form `#[linked_from = "foo"]` where
124 `foo` is the name of a library in either `#[link]` or a `-l` flag. This
125 attribute is currently required to export symbols from a Rust dynamic library
126 on Windows, and it is feature gated behind the `linked_from` feature.
128 On declarations inside an `extern` block, the following attributes are
131 - `link_name` - the name of the symbol that this function or static should be
133 - `linkage` - on a static, this specifies the [linkage
134 type](http://llvm.org/docs/LangRef.html#linkage-types).
138 - `repr` - on C-like enums, this sets the underlying type used for
139 representation. Takes one argument, which is the primitive
140 type this enum should be represented for, or `C`, which specifies that it
141 should be the default `enum` size of the C ABI for that platform. Note that
142 enum representation in C is undefined, and this may be incorrect when the C
143 code is compiled with certain flags.
147 - `repr` - specifies the representation to use for this struct. Takes a list
148 of options. The currently accepted ones are `C` and `packed`, which may be
149 combined. `C` will use a C ABI compatible struct layout, and `packed` will
150 remove any padding between fields (note that this is very fragile and may
151 break platforms which require aligned access).
153 ## Macro-related attributes
155 - `macro_use` on a `mod` — macros defined in this module will be visible in the
156 module's parent, after this module has been included.
158 - `macro_use` on an `extern crate` — load macros from this crate. An optional
159 list of names `#[macro_use(foo, bar)]` restricts the import to just those
160 macros named. The `extern crate` must appear at the crate root, not inside
161 `mod`, which ensures proper function of the [`$crate` macro
162 variable](../book/first-edition/macros.html#the-variable-crate).
164 - `macro_reexport` on an `extern crate` — re-export the named macros.
166 - `macro_export` - export a macro for cross-crate usage.
168 - `no_link` on an `extern crate` — even if we load this crate for macros, don't
169 link it into the output.
171 See the [macros section of the
172 book](../book/first-edition/macros.html#scoping-and-macro-importexport) for more information on
175 ## Miscellaneous attributes
177 - `deprecated` - mark the item as deprecated; the full attribute is
178 `#[deprecated(since = "crate version", note = "...")`, where both arguments
180 - `export_name` - on statics and functions, this determines the name of the
182 - `link_section` - on statics and functions, this specifies the section of the
183 object file that this item's contents will be placed into.
184 - `no_mangle` - on any item, do not apply the standard name mangling. Set the
185 symbol for this item to its identifier.
186 - `simd` - on certain tuple structs, derive the arithmetic operators, which
187 lower to the target's SIMD instructions, if any; the `simd` feature gate
188 is necessary to use this attribute.
189 - `unsafe_destructor_blind_to_params` - on `Drop::drop` method, asserts that the
190 destructor code (and all potential specializations of that code) will
191 never attempt to read from nor write to any references with lifetimes
192 that come in via generic parameters. This is a constraint we cannot
193 currently express via the type system, and therefore we rely on the
194 programmer to assert that it holds. Adding this to a Drop impl causes
195 the associated destructor to be considered "uninteresting" by the
196 Drop-Check rule, and thus it can help sidestep data ordering
197 constraints that would otherwise be introduced by the Drop-Check
198 rule. Such sidestepping of the constraints, if done incorrectly, can
199 lead to undefined behavior (in the form of reading or writing to data
200 outside of its dynamic extent), and thus this attribute has the word
201 "unsafe" in its name. To use this, the
202 `unsafe_destructor_blind_to_params` feature gate must be enabled.
203 - `doc` - Doc comments such as `/// foo` are equivalent to `#[doc = "foo"]`.
204 - `rustc_on_unimplemented` - Write a custom note to be shown along with the error
205 when the trait is found to be unimplemented on a type.
206 You may use format arguments like `{T}`, `{A}` to correspond to the
207 types at the point of use corresponding to the type parameters of the
208 trait of the same name. `{Self}` will be replaced with the type that is supposed
209 to implement the trait but doesn't. To use this, the `on_unimplemented` feature gate
211 - `must_use` - on structs and enums, will warn if a value of this type isn't used or
212 assigned to a variable. You may also include an optional message by using
213 `#[must_use = "message"]` which will be given alongside the warning.
215 ### Conditional compilation
217 Sometimes one wants to have different compiler outputs from the same code,
218 depending on build target, such as targeted operating system, or to enable
221 Configuration options are boolean (on or off) and are named either with a
222 single identifier (e.g. `foo`) or an identifier and a string (e.g. `foo = "bar"`;
223 the quotes are required and spaces around the `=` are unimportant). Note that
224 similarly-named options, such as `foo`, `foo="bar"` and `foo="baz"` may each be set
225 or unset independently.
227 Configuration options are either provided by the compiler or passed in on the
228 command line using `--cfg` (e.g. `rustc main.rs --cfg foo --cfg 'bar="baz"'`).
229 Rust code then checks for their presence using the `#[cfg(...)]` attribute:
232 // The function is only included in the build when compiling for macOS
233 #[cfg(target_os = "macos")]
238 // This function is only included when either foo or bar is defined
239 #[cfg(any(foo, bar))]
240 fn needs_foo_or_bar() {
244 // This function is only included when compiling for a unixish OS with a 32-bit
246 #[cfg(all(unix, target_pointer_width = "32"))]
251 // This function is only included when foo is not defined
258 This illustrates some conditional compilation can be achieved using the
259 `#[cfg(...)]` attribute. `any`, `all` and `not` can be used to assemble
260 arbitrarily complex configurations through nesting.
262 The following configurations must be defined by the implementation:
264 * `target_arch = "..."` - Target CPU architecture, such as `"x86"`,
265 `"x86_64"` `"mips"`, `"powerpc"`, `"powerpc64"`, `"arm"`, or
266 `"aarch64"`. This value is closely related to the first element of
267 the platform target triple, though it is not identical.
268 * `target_os = "..."` - Operating system of the target, examples
269 include `"windows"`, `"macos"`, `"ios"`, `"linux"`, `"android"`,
270 `"freebsd"`, `"dragonfly"`, `"bitrig"` , `"openbsd"` or
271 `"netbsd"`. This value is closely related to the second and third
272 element of the platform target triple, though it is not identical.
273 * `target_family = "..."` - Operating system family of the target, e. g.
274 `"unix"` or `"windows"`. The value of this configuration option is defined
275 as a configuration itself, like `unix` or `windows`.
276 * `unix` - See `target_family`.
277 * `windows` - See `target_family`.
278 * `target_env = ".."` - Further disambiguates the target platform with
279 information about the ABI/libc. Presently this value is either
280 `"gnu"`, `"msvc"`, `"musl"`, or the empty string. For historical
281 reasons this value has only been defined as non-empty when needed
282 for disambiguation. Thus on many GNU platforms this value will be
283 empty. This value is closely related to the fourth element of the
284 platform target triple, though it is not identical. For example,
285 embedded ABIs such as `gnueabihf` will simply define `target_env` as
287 * `target_endian = "..."` - Endianness of the target CPU, either `"little"` or
289 * `target_pointer_width = "..."` - Target pointer width in bits. This is set
290 to `"32"` for targets with 32-bit pointers, and likewise set to `"64"` for
292 * `target_has_atomic = "..."` - Set of integer sizes on which the target can perform
293 atomic operations. Values are `"8"`, `"16"`, `"32"`, `"64"` and `"ptr"`.
294 * `target_vendor = "..."` - Vendor of the target, for example `apple`, `pc`, or
296 * `test` - Enabled when compiling the test harness (using the `--test` flag).
297 * `debug_assertions` - Enabled by default when compiling without optimizations.
298 This can be used to enable extra debugging code in development but not in
299 production. For example, it controls the behavior of the standard library's
300 `debug_assert!` macro.
302 You can also set another attribute based on a `cfg` variable with `cfg_attr`:
308 This is the same as `#[b]` if `a` is set by `cfg`, and nothing otherwise.
310 Lastly, configuration options can be used in expressions by invoking the `cfg!`
311 macro: `cfg!(a)` evaluates to `true` if `a` is set, and `false` otherwise.
313 ### Lint check attributes
315 A lint check names a potentially undesirable coding pattern, such as
316 unreachable code or omitted documentation, for the static entity to which the
319 For any lint check `C`:
321 * `allow(C)` overrides the check for `C` so that violations will go
323 * `deny(C)` signals an error after encountering a violation of `C`,
324 * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint
326 * `warn(C)` warns about violations of `C` but continues compilation.
328 The lint checks supported by the compiler can be found via `rustc -W help`,
329 along with their default settings. [Compiler
330 plugins][unstable book plugin] can provide additional lint checks.
334 // Missing documentation is ignored here
335 #[allow(missing_docs)]
336 pub fn undocumented_one() -> i32 { 1 }
338 // Missing documentation signals a warning here
339 #[warn(missing_docs)]
340 pub fn undocumented_too() -> i32 { 2 }
342 // Missing documentation signals an error here
343 #[deny(missing_docs)]
344 pub fn undocumented_end() -> i32 { 3 }
348 This example shows how one can use `allow` and `warn` to toggle a particular
352 #[warn(missing_docs)]
354 #[allow(missing_docs)]
356 // Missing documentation is ignored here
357 pub fn undocumented_one() -> i32 { 1 }
359 // Missing documentation signals a warning here,
360 // despite the allow above.
361 #[warn(missing_docs)]
362 pub fn undocumented_two() -> i32 { 2 }
365 // Missing documentation signals a warning here
366 pub fn undocumented_too() -> i32 { 3 }
370 This example shows how one can use `forbid` to disallow uses of `allow` for
374 #[forbid(missing_docs)]
376 // Attempting to toggle warning signals an error here
377 #[allow(missing_docs)]
379 pub fn undocumented_too() -> i32 { 2 }
385 Some primitive Rust operations are defined in Rust code, rather than being
386 implemented directly in C or assembly language. The definitions of these
387 operations have to be easy for the compiler to find. The `lang` attribute
388 makes it possible to declare these operations. For example, the `str` module
389 in the Rust standard library defines the string equality function:
393 pub fn eq_slice(a: &str, b: &str) -> bool {
398 The name `str_eq` has a special meaning to the Rust compiler, and the presence
399 of this definition means that it will use this definition when generating calls
400 to the string equality function.
402 The set of language items is currently considered unstable. A complete
403 list of the built-in language items will be added in the future.
405 ### Inline attributes
407 The inline attribute suggests that the compiler should place a copy of
408 the function or static in the caller, rather than generating code to
409 call the function or access the static where it is defined.
411 The compiler automatically inlines functions based on internal heuristics.
412 Incorrectly inlining functions can actually make the program slower, so it
413 should be used with care.
415 `#[inline]` and `#[inline(always)]` always cause the function to be serialized
416 into the crate metadata to allow cross-crate inlining.
418 There are three different types of inline attributes:
420 * `#[inline]` hints the compiler to perform an inline expansion.
421 * `#[inline(always)]` asks the compiler to always perform an inline expansion.
422 * `#[inline(never)]` asks the compiler to never perform an inline expansion.
426 The `derive` attribute allows certain traits to be automatically implemented
427 for data structures. For example, the following will create an `impl` for the
428 `PartialEq` and `Clone` traits for `Foo`, the type parameter `T` will be given
429 the `PartialEq` or `Clone` constraints for the appropriate `impl`:
432 #[derive(PartialEq, Clone)]
439 The generated `impl` for `PartialEq` is equivalent to
442 # struct Foo<T> { a: i32, b: T }
443 impl<T: PartialEq> PartialEq for Foo<T> {
444 fn eq(&self, other: &Foo<T>) -> bool {
445 self.a == other.a && self.b == other.b
448 fn ne(&self, other: &Foo<T>) -> bool {
449 self.a != other.a || self.b != other.b
454 You can implement `derive` for your own type through [procedural
455 macros](procedural-macros.html).
457 ### Compiler Features
459 Certain aspects of Rust may be implemented in the compiler, but they're not
460 necessarily ready for every-day use. These features are often of "prototype
461 quality" or "almost production ready", but may not be stable enough to be
462 considered a full-fledged language feature.
464 For this reason, Rust recognizes a special crate-level attribute of the form:
467 #![feature(feature1, feature2, feature3)]
470 This directive informs the compiler that the feature list: `feature1`,
471 `feature2`, and `feature3` should all be enabled. This is only recognized at a
472 crate-level, not at a module-level. Without this directive, all features are
473 considered off, and using the features will result in a compiler error.
475 The currently implemented features of the reference compiler are documented in
478 If a feature is promoted to a language feature, then all existing programs will
479 start to receive compilation warnings about `#![feature]` directives which enabled
480 the new feature (because the directive is no longer necessary). However, if a
481 feature is decided to be removed from the language, errors will be issued (if
482 there isn't a parser error first). The directive in this case is no longer
483 necessary, and it's likely that existing code will break if the feature isn't
486 If an unknown feature is found in a directive, it results in a compiler error.
487 An unknown feature is one which has never been recognized by the compiler.
489 [The Unstable Book]: https://doc.rust-lang.org/nightly/unstable-book/
490 [unstable book plugin]: ../unstable-book/language-features/plugin.html#lint-plugins