FAQ - Help and questions

How do modules and pub work in Rust, and how do I split code into files?

#modules#visibility#basicspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Items are private to their module by default. Mark them pub to let the parent and others see them. A module is declared with mod name, either inline in braces or as a file name.rs (or name/mod.rs) next to the parent file. use brings a path into scope so you can write short names.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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).

src/main.rsrust
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());
}
text
Ada: 50
50

How to put a module in its own file#

  1. In src/main.rs (or lib.rs) write mod bank;, with a semicolon and no braces.
  2. Create src/bank.rs with the module's contents (without the mod bank { } wrapper).
  3. A submodule report inside it goes in src/bank/report.rs, declared with mod report; in bank.rs.
  4. Refer to items by path (bank::Account) or bring them in with use bank::Account;.

Common mistakes#

  • Creating bank.rs and forgetting mod bank; in the parent. Rust only compiles files that a mod declaration names, so the file is silently ignored and the first sign is an unresolved name.
  • Making everything pub to get past errors. Expose the smallest surface you can; pub(crate) shares an item with the whole crate but not with other crates.
  • Confusing use with mod: use shortens a path, mod creates the module.
    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet