Rust Tutorial: Modules and Crates
Organise code with mod, control visibility with pub, and use the use keyword.
Code organisation
Rust organises code into modules (within a file) and crates (packages). Visibility is private by default — you opt in to public with `pub`.
What you'll learn in this Rust modules and crates tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Inline modules — Define a module with `mod`. Items inside are private by default.
- Nested modules — Modules can be nested. Paths use :: separators.
- use to shorten paths — `use` brings a path into scope so you don't have to repeat it.
- use with as — `as` renames an import to avoid conflicts or shorten long names.
- super and self — `super` refers to the parent module. `self` refers to the current module.
- pub struct fields — Struct fields are private by default. Mark them `pub` individually.
- use glob imports — `use module::*` imports everything public from a module.
- External crates — External crates are listed in Cargo.toml. Use them with `use`.
Rust Modules and Crates concepts covered
- Code organisation