An item is a component of a crate, and a source file is a sequence of items. Items are declared in modules and may also be declared inside blocks. They are fixed at compile time and live for the whole program (Reference: Items).
The kinds of item
Item:
OuterAttribute* ( VisItem | MacroItem )
VisItem:
Visibility? (
Module | ExternCrate | UseDeclaration | Function | TypeAlias
| Struct | Enumeration | Union | ConstantItem | StaticItem
| Trait | Implementation | ExternBlock )
MacroItem:
MacroInvocationSemi | MacroRulesDefinition
This page covers modules, extern crate, use, functions, type
aliases, constants, statics and extern blocks. Other items have their own pages:
structs, enums and unions,
traits and implementations and
macros. Generic parameters on items are on the
Generics page.
Modules
A module is a named container for items. Module names live in the type namespace.
A module with a body keeps its items inline; one without a body, mod name;,
loads a file, as described under
How mod maps to
files. Modules may be nested to any depth.
mod math {
pub mod trig {
pub fn sin(x: f64) -> f64 { x.sin() }
}
pub fn double(x: i32) -> i32 { x * 2 }
fn helper() {} // private to math
}
mod io; // loaded from io.rs or io/mod.rs
Visibility
Visibility:
pub
| pub ( crate )
| pub ( self )
| pub ( super )
| pub ( in SimplePath )
Items are private by default: visible in the module that defines them and its descendants (Reference: Visibility and privacy).
| Form | Visible |
|---|---|
| none | The current module and its children |
pub | Anywhere the enclosing modules are visible |
pub(crate) | The whole current crate |
pub(super) | The parent module; the same as pub(in super) |
pub(self) | The current module; the same as no qualifier |
pub(in path) | The given ancestor module. In edition 2018 and later the path must start with crate, self or super |
- A visibility only adds a restriction. To reach an item, every module on the way must also be visible.
- Enum variants take the visibility of the enum. Trait items take the visibility of the trait, and items in a trait implementation take the trait’s visibility.
- A
pub usere-exports a name and can publish a path whose original is private.
extern crate
ExternCrate: extern crate CrateRef AsClause? ;
CrateRef: IDENTIFIER | self
AsClause: as ( IDENTIFIER | _ )
An extern crate declaration says the crate depends on another crate and
binds its name in the type namespace. At the crate root it also adds the name to the
extern prelude. In edition 2018 and later this is rarely needed, because Cargo’s
dependencies can be named directly in paths. It is still used for crates that come with
the compiler and for #[macro_use].
asrenames the crate.extern crate foo as _;links it without binding a name.extern crate self as my_crate;gives the current crate a name and requires theas.- Cargo turns a hyphenated package name into an underscored crate name, so
hello-worldbecomeshello_world. #[no_link]imports the crate’s macros without linking it.
Use declarations
UseDeclaration: use UseTree ;
UseTree:
( SimplePath? :: )? *
| ( SimplePath? :: )? { ( UseTree ( , UseTree )* ,? )? }
| SimplePath ( as ( IDENTIFIER | _ ) )?
use std::collections::HashMap; // one name
use std::collections::{BTreeSet, hash_map}; // several, nested
use std::io::{self, Read}; // io itself and io::Read
use std::fmt::Result as FmtResult; // rename
use std::collections::*; // glob import
use self::foo::Zoo as _; // bring a trait in, no name
pub use self::inner::api; // re-export
use crate::util::config; // from the crate root
| Rule | Detail |
|---|---|
| What can be imported | Items, enum variants, built-in types, attributes, derive macros and macro_rules macros. Not associated items, generic parameters, local variables, or paths through Self |
| Namespaces | A use binds a name in every namespace the target has. self imports only the type namespace |
| Visibility | Private to the module by default. pub use is a re-export |
| Paths, edition 2015 | Relative to the crate root. extern crate is required for external crates |
| Paths, edition 2018 and later | Relative to the current scope and may name external crates directly. A leading :: means the extern prelude |
| Glob imports | * must be the last segment. Items and named imports in the same namespace shadow names that came from a glob. use self::*; in a module is not allowed |
| Underscore imports | as _ brings a trait’s methods into scope without binding its name. Each one is unique, so a macro can emit it twice |
self in braces | Binds the parent name itself. Allowed only when the parent is a module, enum or trait |
| Bare keywords | crate, $crate, self and super must use as: use crate as root; |
| Enum variants through aliases | Not allowed: use MyAlias::Variant fails even when MyAlias names the enum |
| Duplicates | Imports cannot bind the same name twice in one namespace of a module or block |
Functions
Function:
FunctionQualifiers fn IDENTIFIER GenericParams?
( FunctionParameters? ) ( -> Type )? WhereClause?
( BlockExpression | ; )
FunctionQualifiers:
const? async? ItemSafety? ( extern Abi? )?
ItemSafety: safe | unsafe
Abi: STRING_LITERAL | RAW_STRING_LITERAL
SelfParam: ShorthandSelf | TypedSelf
ShorthandSelf: ( & | & Lifetime )? mut? self
TypedSelf: mut? self : Type
fn add(x: i32, y: i32) -> i32 { x + y }
const fn square(x: u32) -> u32 { x * x }
async fn fetch() -> u32 { 1 }
unsafe fn raw_read(p: *const u8) -> u8 { unsafe { *p } }
extern "C" fn callback(x: i32) -> i32 { x + 1 }
fn first((value, _): (i32, i32)) -> i32 { value } // a pattern as parameter
The qualifiers must appear in the order in the grammar: const,
async, then safe or unsafe, then
extern. safe is valid only in extern blocks.
- Parameters are patterns. They must be irrefutable. The first
may be a
selfparameter, which makes the function a method (see Methods). Methods may appear only in traits and implementations. - Return. With no
-> Typethe return type is(). The body’s final expression without a semicolon is the value returned. - A body is omitted only in a trait or an extern block.
| Qualifier | Meaning |
|---|---|
const | May be called in const contexts. Cannot be async |
async | Returns a future that runs the body when polled. Not in edition 2015. See Concurrency and async |
unsafe | Calling it requires an unsafe block |
extern "ABI" | Uses the named calling convention. extern fn with no string means "C"; a function with no extern uses "Rust" |
Type aliases
TypeAlias:
type IDENTIFIER GenericParams? ( : Bounds? )? WhereClause?
( = Type WhereClause? )? ;
A type alias gives a new name to a type in the type namespace. A standalone alias
must have the = Type and no bounds. In a trait the alias is an
associated type and in a trait
implementation it must have the type.
type Point = (u8, u8);
type Result<T> = std::result::Result<T, std::io::Error>;
struct MyStruct(u32);
use MyStruct as UseAlias;
type TypeAlias = MyStruct;
let _ = UseAlias(5); // works
// let _ = TypeAlias(5); // error: an alias cannot call the constructor
A type alias to a tuple or unit struct cannot be used as its constructor; a
use … as import can.
Constants
ConstantItem:
const ( IDENTIFIER | _ ) : Type ( = Expression )? ;
A constant is an unnamed value computed at compile time and inlined at each use.
It is not a single memory location. Its initialiser must be a
constant expression, and may
be omitted only in a trait. A reference type in a constant is implicitly
'static.
const MAX: u32 = 100_000;
const GREETING: &str = "hello"; // &'static str
const _: () = assert!(MAX > 0); // an unnamed compile-time check
- A free constant is unnamed when its name is
_. Macros may emit the same unnamed constant more than once. - Free constants are always evaluated at compile time, even in an unused function.
- A constant may have a destructor. Each use produces its own value, and that value’s destructor runs when it goes out of scope.
- Associated constants live in traits and implementations and may be generic.
Statics
StaticItem:
ItemSafety? static mut? IDENTIFIER : Type ( = Expression )? ;
A static is a single memory location that lives for the whole program. Its initialiser must be a constant expression. The address of a non-zero-sized static is distinct from other statics, heap allocations and stack variables.
static COUNT: AtomicU32 = AtomicU32::new(0);
static GREETING: &str = "hello";
static mut LEVELS: u32 = 0;
unsafe fn bump() -> u32 {
unsafe { LEVELS += 1; LEVELS }
}
- The type must be
Sync, so shared access from any thread is safe.static mutis exempt from this. - The destructor of a static is never run.
- Reading or writing a
static mutrequiresunsafe. In edition 2024, the lintstatic_mut_refsdenies references to one by default. - A non-
mutstatic without interior mutability may be placed in read-only memory. - A static defined in a generic scope, such as a blanket implementation, produces exactly one static, not one per set of type arguments.
- Prefer a
constunless a fixed address, interior mutability or a very large value is needed.
Extern blocks
ExternBlock:
unsafe? extern Abi? { InnerAttribute* ExternalItem* }
ExternalItem:
OuterAttribute* ( MacroInvocationSemi | Visibility? StaticItem | Visibility? Function )
An extern block declares functions and statics defined outside Rust, typically in C
(Reference: External blocks). In edition 2024 the block must be written
unsafe extern. In earlier editions unsafe is optional.
unsafe extern "C" {
pub safe fn abs(x: i32) -> i32; // callable without unsafe
pub unsafe fn strlen(s: *const u8) -> usize; // requires unsafe to call
static environ: *const *const u8; // requires unsafe to read
}
- Functions have no body. Parameters must be identifiers or
_. Only thesafeandunsafequalifiers are allowed, and without one a function is implicitlyunsafe. - Statics have no initialiser. Accessing one is
unsafeunless it is markedsafe, whether or not it ismut. - Before edition 2024,
safeandunsafeitem qualifiers are allowed only if the block is writtenunsafe. - A trailing
...makes the function variadic, as inunsafe fn printf(fmt: *const u8, ...) -> i32;.
ABI strings
| ABI | Meaning |
|---|---|
"Rust" | The default ABI of Rust functions; not stable |
"C" | The target’s default C convention |
"system" | The same as "C" except on 32-bit x86 Windows, where it is "stdcall" for non-variadic functions |
"C-unwind", "system-unwind" | The same as "C" and "system", but unwinding across the boundary is allowed |
"cdecl", "stdcall", "fastcall", "thiscall" | 32-bit x86 only |
"win64", "sysv64" | x86-64 only |
"aapcs" | 32-bit ARM only |
"efiapi" | UEFI |
Most ABIs also have an -unwind form. Omitting the ABI string from an
extern block means "C", but writing it is recommended.
Link attributes
| Attribute | Effect |
|---|---|
#[link(name = "foo")] | Links a native library. Optional kind: dylib (default), static, framework (macOS), raw-dylib (Windows) |
#[link_name = "actual"] | Sets the symbol name of one function or static |
#[link_ordinal(15)] | Sets the numeric ordinal on Windows, with raw-dylib only |