Answer#
A module is a named container for functions, types and other modules. Privacy is the main rule: code can see an item if the item is in the same module, in a parent module, or is marked pub. A struct's fields are private unless marked pub too, which lets a type guard its own invariants (here, balance can only change through deposit).
mod bank {
pub struct Account {
pub owner: String,
balance: i64, // private: only code inside `bank` can touch it
}
impl Account {
pub fn open(owner: &str) -> Account {
Account { owner: owner.to_string(), balance: 0 }
}
pub fn deposit(&mut self, amount: i64) {
self.balance += amount;
}
pub fn balance(&self) -> i64 {
self.balance
}
}
pub mod report {
pub fn line(a: &super::Account) -> String {
format!("{}: {}", a.owner, a.balance) // child modules may see the parent's private items
}
}
}
use bank::Account;
fn main() {
let mut acc = Account::open("Ada");
acc.deposit(50);
println!("{}", bank::report::line(&acc));
println!("{}", acc.balance());
}Ada: 50
50How to put a module in its own file#
- In
src/main.rs(orlib.rs) writemod bank;, with a semicolon and no braces. - Create
src/bank.rswith the module's contents (without themod bank { }wrapper). - A submodule
reportinside it goes insrc/bank/report.rs, declared withmod report;inbank.rs. - Refer to items by path (
bank::Account) or bring them in withuse bank::Account;.
Common mistakes#
- Creating
bank.rsand forgettingmod bank;in the parent. Rust only compiles files that amoddeclaration names, so the file is silently ignored and the first sign is an unresolved name. - Making everything
pubto get past errors. Expose the smallest surface you can;pub(crate)shares an item with the whole crate but not with other crates. - Confusing
usewithmod:useshortens a path,modcreates the module.