The Rust Reference
The Rust Reference
web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/reference/attributes.html
For now, this reference is a best-effort document. We strive for validity and completeness,
but are not yet there. In the future, the docs and lang teams will work together to figure out
how best to do this. Until then, this is a best-effort attempt. If you find something wrong or
missing, file an issue or send in a pull request.
Attributes
Syntax
Attribute :
InnerAttribute | OuterAttribute
InnerAttribute :
#![ MetaItem ]
OuterAttribute :
#[ MetaItem ]
MetaItem :
IDENTIFIER
| IDENTIFIER = LITERAL
| IDENTIFIER ( LITERAL )
| IDENTIFIER ( MetaSeq )
| IDENTIFIER ( MetaSeq , )
MetaSeq :
EMPTY
| MetaItem
| MetaSeq , MetaItem
Any item declaration may have an attribute applied to it. Attributes in Rust are modeled on
Attributes in ECMA-335, with the syntax coming from ECMA-334 (C#). An attribute is a
general, free-form metadatum that is interpreted according to name, convention, and
language and compiler version. Attributes may appear as any of:
1/9
Attributes with a bang ("!") after the hash ("#") apply to the item that the attribute is declared
within. Attributes that do not have a bang after the hash apply to the item that follows the
attribute.
An example of attributes:
// A conditionally-compiled module
#[cfg(target_os = "linux")]
mod bar {
/* ... */
}
Crate-only attributes
crate_name - specify the crate's crate name.
crate_type - see linkage.
no_builtins - disable optimizing certain code patterns to invocations of library
functions that are assumed to exist
no_main - disable emitting the main symbol. Useful when some other object being
linked to defines main.
no_start - disable linking to the native crate, which specifies the "start" language
item.
no_std - disable linking to the std crate.
recursion_limit - Sets the maximum depth for potentially infinitely-recursive compile-
time operations like auto-dereference or macro expansion. The default is #!
[recursion_limit="64"].
windows_subsystem - Indicates that when this crate is linked for a Windows target it will
configure the resulting binary's subsystem via the linker. Valid values for this attribute
are console and windows, corresponding to those two respective subsystems. More
subsystems may be allowed in the future, and this attribute is ignored on non-Windows
targets.
Module-only attributes
2/9
no_implicit_prelude - disable injecting use std::prelude::* in this module.
path - specifies the file to load the module from. #[path="foo.rs"] mod bar; is
equivalent to mod bar { /* contents of foo.rs */ }. The path is taken relative to
the directory that the current module is in.
Function-only attributes
main - indicates that this function should be passed to the entry point, rather than the
function in the crate root named main.
test - indicates that this function is a test function, to only be compiled in case of --
test.
ignore - indicates that this test function is disabled.
should_panic - indicates that this test function should panic, inverting the success
condition.
cold - The function is unlikely to be executed, so optimize it (and calls to it) differently.
FFI attributes
On an extern block, the following attributes are interpreted:
link_args - specify arguments to the linker, rather than just the library name and type.
This is feature gated and the exact behavior is implementation-defined (due to variety
of linker invocation syntax).
link - indicate that a native library should be linked to for the declarations in this block
to be linked correctly. link supports an optional kind key with three possible values:
dylib, static, and framework. See external blocks for more about external blocks.
Two examples: #[link(name = "readline")] and #[link(name =
"CoreFoundation", kind = "framework")].
linked_from - indicates what native library this block of FFI items is coming from. This
attribute is of the form #[linked_from = "foo"] where foo is the name of a library in
either #[link] or a -l flag. This attribute is currently required to export symbols from a
Rust dynamic library on Windows, and it is feature gated behind the linked_from
feature.
link_name - the name of the symbol that this function or static should be imported as.
linkage - on a static, this specifies the linkage type.
See type layout for documentation on the repr attribute which can be used to control type
layout.
Macro-related attributes
3/9
macro_use on a mod — macros defined in this module will be visible in the module's
parent, after this module has been included.
macro_use on an extern crate — load macros from this crate. An optional list of
names #[macro_use(foo, bar)] restricts the import to just those macros named. The
extern crate must appear at the crate root, not inside mod, which ensures proper
function of the $crate macro variable.
no_link on an extern crate — even if we load this crate for macros, don't link it into
the output.
See the macros section of the book for more information on macro scope.
Miscellaneous attributes
export_name - on statics and functions, this determines the name of the exported
symbol.
link_section - on statics and functions, this specifies the section of the object file that
this item's contents will be placed into.
no_mangle - on any item, do not apply the standard name mangling. Set the symbol for
this item to its identifier.
must_use - on structs and enums, will warn if a value of this type isn't used or assigned
to a variable. You may also include an optional message by using #[must_use =
"message"] which will be given alongside the warning.
Deprecation
The deprecated attribute marks an item as deprecated. It has two optional fields, since and
note.
Only public items can be given the #[deprecated] attribute. #[deprecated] on a module is
inherited by all child items of that module.
4/9
rustc will issue warnings on usage of #[deprecated] items. rustdoc will show item
deprecation, including the since version and note, if available.
Here's an example.
#[deprecated(since = "5.2", note = "foo was rarely used. Users should instead use bar")]
pub fn foo() {}
pub fn bar() {}
Documentation
The doc attribute is used to document items and fields. Doc comments are transformed into
doc attributes.
Conditional compilation
Sometimes one wants to have different compiler outputs from the same code, depending on
build target, such as targeted operating system, or to enable release builds.
Configuration options are boolean (on or off) and are named either with a single identifier
(e.g. foo) or an identifier and a string (e.g. foo = "bar"; the quotes are required and spaces
around the = are unimportant). Note that similarly-named options, such as foo, foo="bar"
and foo="baz" may each be set or unset independently.
Configuration options are either provided by the compiler or passed in on the command line
using --cfg (e.g. rustc main.rs --cfg foo --cfg 'bar="baz"'). Rust code then checks
for their presence using the #[cfg(...)] attribute:
5/9
// The function is only included in the build when compiling for macOS
#[cfg(target_os = "macos")]
fn macos_only() {
// ...
}
// This function is only included when compiling for a unixish OS with a 32-bit
// architecture
#[cfg(all(unix, target_pointer_width = "32"))]
fn on_32bit_unix() {
// ...
}
This illustrates some conditional compilation can be achieved using the #[cfg(...)]
attribute. any, all and not can be used to assemble arbitrarily complex configurations
through nesting.
6/9
target_endian = "..." - Endianness of the target CPU, either "little" or "big".
target_pointer_width = "..." - Target pointer width in bits. This is set to "32" for
targets with 32-bit pointers, and likewise set to "64" for 64-bit pointers.
target_has_atomic = "..." - Set of integer sizes on which the target can perform
atomic operations. Values are "8", "16", "32", "64" and "ptr".
target_vendor = "..." - Vendor of the target, for example apple, pc, or simply
"unknown".
test - Enabled when compiling the test harness (using the --test flag).
debug_assertions - Enabled by default when compiling without optimizations. This can
be used to enable extra debugging code in development but not in production. For
example, it controls the behavior of the standard library's debug_assert! macro.
You can also set another attribute based on a cfg variable with cfg_attr:
#[cfg_attr(a, b)]
Lastly, configuration options can be used in expressions by invoking the cfg! macro: cfg!
(a) evaluates to true if a is set, and false otherwise.
The lint checks supported by the compiler can be found via rustc -W help, along with their
default settings. [Compiler plugins][unstable book plugin] can provide additional lint checks.
7/9
pub mod m1 {
// Missing documentation is ignored here
#[allow(missing_docs)]
pub fn undocumented_one() -> i32 { 1 }
This example shows how one can use allow and warn to toggle a particular check on and
off:
#[warn(missing_docs)]
pub mod m2{
#[allow(missing_docs)]
pub mod nested {
// Missing documentation is ignored here
pub fn undocumented_one() -> i32 { 1 }
This example shows how one can use forbid to disallow uses of allow for that lint check:
#[forbid(missing_docs)]
pub mod m3 {
// Attempting to toggle warning signals an error here
#[allow(missing_docs)]
/// Returns 2.
pub fn undocumented_too() -> i32 { 2 }
}
Inline attribute
The inline attribute suggests that the compiler should place a copy of the function or static in
the caller, rather than generating code to call the function or access the static where it is
defined.
8/9
The compiler automatically inlines functions based on internal heuristics. Incorrectly inlining
functions can actually make the program slower, so it should be used with care.
#[inline] and #[inline(always)] always cause the function to be serialized into the crate
metadata to allow cross-crate inlining.
derive
The derive attribute allows certain traits to be automatically implemented for data structures.
For example, the following will create an impl for the PartialEq and Clone traits for Foo, the
type parameter T will be given the PartialEq or Clone constraints for the appropriate impl:
#[derive(PartialEq, Clone)]
struct Foo<T> {
a: i32,
b: T,
}
You can implement derive for your own type through procedural macros.
9/9