Modules and several files
Split a program into files with mod, make items visible with pub, and what is available without crates.
Runs in Zerethon IDE · Rust 1.87
Official Rust documentation ↗
main.rs
mod geometry;
fn main() {
println!("{}", geometry::area(3, 4));
println!("{}", geometry::shapes::NAME);
}
geometry.rs
pub mod shapes {
pub const NAME: &str = "shapes ok";
}
pub fn area(width: i32, height: i32) -> i32 {
width * height
}
Output
12 shapes ok
main.rs (the entry) and geometry.rs next to it.
- The entry file is the crate root.
mod geometry;loadsgeometry.rs(orgeometry/mod.rs) from the same folder; a file that nomodnames is not compiled. - Items are private to their module unless marked
pub. use std::collections::HashMap;brings a name into scope; the whole standard library is available.- There is no Cargo and no network, so crates from crates.io (
rand,regex,serde…) cannot be used.