mod a {
fn g() {
println!("g");
}
pub fn f() {
println!("f");
g();
}
pub mod b {
pub fn h() {
println!("h");
}
}
}
fn main() {
a::f();
a::b::h();
}
src/main.rs
:
mod a;
fn main() {
a::f();
a::b::h();
}
src/a.rs
:
fn g() {
println!("g");
}
pub fn f() {
println!("f");
g();
}
pub mod b;
src/a/b.rs
:
pub fn h() {
println!("h");
}
The use
statements binds a local name to a name from a different module:
src/main.rs
:
mod a;
use a::f;
use a::b::h as hhh;
fn main() {
f();
hhh();
}
It is possible to import multiple names:
src/main.rs
:
mod a;
use a::{f, b::h};
fn main() {
f();
h();
}
Code in a module (including the top level) can see all public declarations, its own private declarations, and private declarations up in the hierarchy, but nothing else.
So this is possible (going back to all modules in the same file):
mod a {
fn g() {
println!("g");
}
pub fn f() {
println!("f");
g();
b::i();
}
pub mod b {
pub fn h() {
println!("h");
crate::a::g(); // up in the hierarchy!
}
pub fn i() { // this pub is needed for b::i() above!
println!("i");
}
}
}
fn main() {
a::f();
a::b::h();
}
self
refers to the current module, super
refers to the module one
up in the hierarchy. crate
refers to the top level of the currently
compiled crate.
src/main.rs
:
mod a {
fn g() {
println!("g");
}
pub fn f() {
println!("f");
self::g();
b::i();
}
pub mod b {
pub fn h() {
println!("h");
super::g(); // up in the hierarchy!
}
pub fn i() {
println!("i");
}
}
}
fn main() {
a::f();
a::b::h();
}
- Rust book: https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html
- Rust book: https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html
- Rust by example: https://doc.rust-lang.org/rust-by-example/mod.html
- Rust reference (paths): https://doc.rust-lang.org/stable/reference/paths.html
- Rust reference (modules): https://doc.rust-lang.org/stable/reference/items/modules.html
- Video: https://youtu.be/iSPQRymGw-4
- Overview: https://gist.github.com/max-itzpapalotl/18f7675a60f6f9603250367bcb63992e