liveBook · Manning

Mod keyword

As explained in Rust Web Development

The mod keyword in Rust declares a module and identifies its source location.

Use `mod` to organize related code into modules and connect a Rust source file to its place in the module tree. A module creates a separate scope: its code needs its own imports, and other code may need a module-qualified path such as `error::Error`. Items are private by default, so expose items or modules with `pub` when other modules need them. section 5.1.1

For a small group of definitions, declare an inline module with `mod error { ... }`. To move that code into `error.rs`, declare `mod error;` in the parent file instead; the filename supplies the module name. `mod` declares the module, while `use` brings a module or path into use in a file. section 5.1.2 section 5.4

As code moves into folders, declare child modules in `mod.rs`, for example with `pub mod question;`. The parent module then connects those files to the application’s module tree. section 5.1.2

$ tree .
.
├── Cargo.lock
├── Cargo.toml
├── questions.json
└── src
   ├── error.rs
   ├── main.rs
   ├── routes
   │   ├── answer.rs
   │   ├── mod.rs
   │   └── question.rs
   └── types
       ├── answer.rs
       ├── mod.rs
       ├── pagination.rs
       └── question.rs

3 directories, 12 files

A sample project tree shows module files grouped under `routes` and `types`, alongside `main.rs` and `error.rs`. section 5.1.2 section 5.4

How Rust Web Development covers it

How deep it goes
Works through inline and file-based declarations, scope, visibility, and paths using an error-handling refactor.
Examples
Uses an error-handling module and a project tree containing `routes`, `types`, and `error.rs`.
What you can do after
Apply `mod` to declare inline or file-backed modules and expose nested files through `mod.rs`.
How it connects
Connects modules with `use`, `pub` visibility, module paths, and Rust’s file-based source tree.

Also explained in

Compare how 2 books explain mod keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Web Development. The section links point to the parts of the book it draws on.