Modules and Crates
Organize code with modules, paths, and crate visibility. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Busque em todas as páginas da documentação
Organize code with modules, paths, and crate visibility. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Declare modules; files map to paths.
mod net {
pub fn ping() -> &'static str { "pong" }
}
net::ping() // "pong"Bring paths into scope; rename with as.
use std::collections::HashMap as Map;
let m: Map<i32, i32> = Map::new();
m.len() // 0pub, pub(crate), pub(super) control access.
mod a {
pub(crate) fn f() -> i32 { 1 }
}
a::f() // 1crate:: from root; super:: parent module.
mod outer {
pub fn x() -> i32 { 2 }
pub mod inner {
pub fn y() -> i32 { super::x() }
}
}
outer::inner::y() // 2Expose child items at a higher path.
mod raw { pub fn f() -> i32 { 3 } }
pub use raw::f;
f() // 3mod foo; loads foo.rs or foo/mod.rs - structure only note.
// src/lib.rs: mod foo;
// src/foo.rs: pub fn f() {}Dependencies from Cargo.toml via extern crate paths.
// use serde::Serialize;
// after: serde = "1" in Cargo.tomlRe-export common items in a prelude module.
mod prelude {
pub use std::collections::HashMap;
}
use prelude::*;
HashMap::<u8, u8>::new().len() // 0Compile items only on some targets/features.
#[cfg(test)]
fn only_test() -> i32 { 1 }
// available under cargo testOptional deps gated by features in Cargo.toml.
// [features]
// full = ["dep:serde"]
// enable with: cargo build --features fullMulti-crate repos use [workspace] members.
// [workspace]
// members = ["crates/*"]lib.rs library root; main.rs binary root.
// src/lib.rs exports; src/main.rs calls the lib#[path = "..."] overrides module file path - use sparingly.
// #[path = "alt.rs"]
// mod m;use module::* imports public names - keep limited.
mod m { pub const X: i32 = 1; }
use m::*;
X // 1use self::child::Item relative to current module.
mod child { pub const N: i32 = 9; }
use self::child::N;
N // 9Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Revisado por Chris St. John·Última atualização: 18 de jul. de 2026