Skip to main content

Modules, paths and visibility

Everything is private by default. A `mod` block creates a namespace, `pub` opens an item up to the parent module, and `use` brings a path into scope so you can stop typing it out.

In a real project each file is a module and each directory a module tree, rooted at `src/main.rs` or `src/lib.rs`. Cargo builds it, `cargo fmt` formats it, `cargo clippy` lints it, and `cargo doc` turns your `///` comments into browsable documentation.

The example below is a single file, which is exactly how a growing program starts before you split it up.

Reaching a private item

mod inner {
    fn secret() -> i32 { 42 }
}

fn main() {
    println!("{}", inner::secret()); // error[E0603]
}

error[E0603]: function `secret` is private

Mark it `pub fn secret()`. Privacy is per-module, so a parent cannot reach into a child's private items — that boundary is what keeps refactors safe.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust