Module
Note: 🚧 This page is a work in progress 🚧
A module is a unit of Rust code that encapsulates its content. Modules form a hierarchy (the module tree) within a crate. A module can correspond to a file or a part of a file. Submodules are usually grouped together in a directory, although that is not a necessity.
Inline modules[edit]
Modules can be declared with a mod
block, these can be arbitrarily nested:
mod a {
mod b {}
mod c {}
}
mod d {}
Modules are usually written in the global scope (outside of other items), but they can also be declared within a function:
fn main() {
mod hello {
pub fn world() {
println!("Hello world!");
}
}
hello::world();
}
A mod
block creates a new global scope. This means that it can contain items, but no statements or expressions:
mod a {
let x = 5; // error
}
Visibility[edit]
Main article: Visibility
Items can have a visibility modifier (e.g. pub
), which controls access from other modules. Example:
// this struct is "private", it can only
// be accessed in the current module:
struct Foo;
// this struct is visible in the entire crate:
pub(crate) struct Baz;
// this struct is "public", it can be accessed
// anywhere, even in different crates:
pub struct Bar;
Possible visibility modifiers[edit]
- No modifier: The item is only visible in the current module
pub(self)
: Equivalent to no modifierpub(super)
: The item is only visible in the parent modulepub(crate)
: The item is only visible in the current cratepub(in path)
: The item is only visible in the specified path. Any path can be specified, e.g.pub(in crate::foo::bar)
, as long as it refers to an ancestor of the current module.pub
: The item is visible everywhere
Module paths[edit]
To access items in a different module, paths are used. A path is a sequence of path segments, separated by ::
. Relative paths begin in the current module. Absolute paths, which start with the crate
keyword, begin at the crate root. The parent module can be referred to with the super
keyword:
// root module
const ANSWER: u32 = 42;
mod inner {
mod inner2 {
fn answer() -> u32 {
crate::ANSWER
}
}
}
Root modules[edit]
The root module of a crate is the module that contains all other modules. If the crate is a binary, it also contains the main
function (the entry point for the application).
In library crates, the root module resides in src/lib.rs
by default. In binary crates, the default location is src/main.rs
. This can be overridden. If a crate has multiple targets, it also has multiple module trees.
The module root of other crates is usually referenced with their crate name (substituting -
with _
):
// import items from `async-std`:
use async_std::{main, test};
If there is both a binary target and a library target, the library can be referenced from the binary in the same way:
// src/lib.rs
// crate `my-project`
pub fn hello_world() {
println!("Hello world!");
}
// src/main.rs
fn main() {
my_project::hello_world();
}