liveBook · Manning

Module

As explained in Rust Web Development

A module is a unit of organization in Rust code that groups related items and can control their visibility.

A module groups related Rust items in a separate scope and controls their visibility. It can keep a growing web application’s main.rs focused on connecting components and starting the server. section 5.0 section 5.1.1

To extract error handling into a module:

  • Declare a named module with mod error { ... } and move the related error types and functions inside it. Module names conventionally use snake_case. section 5.1.1
  • Move required imports into the new scope. For example, import warp::reject::Reject inside error so its implementation can find the trait. section 5.1.1
  • Update callers to use a path such as error::Error. Mark the enum and any functions callers need with pub; items are private by default. section 5.1.1
  • Run cargo build and use unresolved-name or privacy errors to find imports, paths, and visibility that still need adjustment. section 5.1.1

Moving a module into a file

Move the error items into src/error.rs and declare mod error; in main.rs. The file itself supplies the module’s scope, so keeping an additional mod error { ... } inside it would create a nested error::error::Error path. Remove that redundant wrapper to retain error::Error. The mod declaration makes the module available; use brings a path into scope for use in a file. 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

This project tree separates error handling into a file and groups route and type submodules into folders. Each folder’s mod.rs declares its submodules; pub mod exposes the submodules needed elsewhere. section 5.1.2

The same approach can isolate server configuration in src/config.rs. Main can then create a config value in one line while the module groups the available settings. section 10.4.3

How Rust Web Development covers it

How deep it goes
Walks through scope, imports, visibility, file extraction, nested modules, and folder declarations using compiler errors.
Examples
Uses an error-handling module, route and type folders, and a server configuration module.
What you can do after
Build modules from scratch to group related Rust items, expose needed interfaces, and split an application across files.
How it connects
Connects modules to scope, visibility, imports, error handling, and configuration.

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.