Learn Rust · 5/14

Managing Growing Projects: Packages and Modules

6 min read

Managing Growing Projects: Packages and Modules 🦀

As your Rust projects grow, keeping your code organized becomes crucial for maintainability and collaboration. This guide will walk you through Rust's module system, which helps you structure your code effectively.

Imagine building a large Lego castle. You wouldn't just have a giant pile of bricks. You'd likely have smaller, pre-assembled sections like towers, walls, and gates that you then connect. Rust's module system works similarly, allowing you to build and organize your code in manageable, interconnected pieces.

1. Packages and Crates: The Rust Module System 📦

The Problem: When you start a new project, you might have all your code in a single file. But as the project expands, this becomes messy and hard to navigate. You need a way to group related functionality.

The Solution: Rust's organizational structure starts with packages and crates.

  • Crate: A crate is the smallest unit of compilation in Rust. It's essentially a collection of code that gets compiled together. A crate can be a binary (an executable program) or a library (a collection of reusable code).

    • A binary crate has a main function and is intended to be run. The entry point for a binary crate is typically src/main.rs.
    • A library crate provides functionality for other projects to use and its entry point is usually src/lib.rs.
  • Package: A package is a bundle of one or more crates. It contains a Cargo.toml file, which is the manifest for your package. This file describes how to build the crates within the package, including their dependencies. A package can have multiple binary crates but at most one library crate.

When you run cargo new my_project, Cargo creates a new package for you with a Cargo.toml file and a src directory containing main.rs, which is the root of a binary crate with the same name as your package.

Real-World Analogy: Think of a cookbook as a package. The entire book is a cohesive unit with a table of contents and instructions (Cargo.toml). Each chapter, focusing on a specific type of dish (e.g., "Appetizers," "Main Courses"), can be thought of as a crate.


2. Defining Modules to Control Scope and Privacy 🚪

The Problem: Even within a single crate, you'll want to further organize your code. For instance, in a web server, you might have code for handling requests, connecting to a database, and processing data. Throwing it all into main.rs would be chaotic.

The Solution: Modules are used to group related code within a crate. They allow for better organization and control over the privacy of your code. By default, all items (functions, structs, etc.) in a module are private to that module. You can use the pub keyword to make them public and accessible from outside the module.

You define a module using the mod keyword:

rust
// In src/main.rs or src/lib.rs

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }

    mod serving {
        fn take_order() {}
        fn serve_order() {}
        fn take_payment() {}
    }
}

In this example:

  • We have a front_of_house module.
  • Inside front_of_house, we have a public hosting submodule and a private serving submodule.
  • The add_to_waitlist function inside hosting is public.
  • The functions inside serving are private by default.

This structure allows us to separate the concerns of our "restaurant" and control which parts are exposed as the public API.

Fun Fact: The concept of modules and controlling visibility is a cornerstone of a principle called "encapsulation" in programming. It's like having a "staff only" area in a restaurant – customers don't need to know how the kitchen works to enjoy their meal.


3. Paths for Referring to an Item in the Module Tree 🗺️

The Problem: Now that we have our code organized into modules, how do we actually use the functions and other items defined within them?

The Solution: We use paths to refer to items in the module tree, much like you use paths to navigate a file system. A path is a sequence of identifiers separated by double colons (::).

There are two types of paths:

  • Absolute Path: Starts from the crate root using the crate keyword.
  • Relative Path: Starts from the current module.

Let's expand on our restaurant example:

rust
// In src/lib.rs

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();
}

Here, eat_at_restaurant is at the crate root, so both the absolute and relative paths achieve the same thing.

super Keyword: To refer to an item in the parent module, you can use the super keyword, which is similar to .. in a file system path.

Separating Modules into Different Files: As your modules grow, you can move them into their own files to keep your crate root clean.

  • If you have mod front_of_house; in src/lib.rs, the compiler will look for the module's code in src/front_of_house.rs or src/front_of_house/mod.rs.

4. Bringing Paths into Scope with the use Keyword शॉर्टकट (Shortcut)

The Problem: Writing out long paths to access items can be repetitive and make your code less readable.

The Solution: The use keyword allows you to bring a path into the current scope, creating a shortcut to that item.

rust
// In src/lib.rs

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

use crate::front_of_house::hosting; // Bring the hosting module into scope

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist(); // Now we can just use hosting
    hosting::add_to_waitlist();
}

Common use Patterns:

  • Bringing a module into scope: use std::collections::HashMap;
  • Bringing nested items into scope: use std::collections::{HashMap, HashSet};
  • The glob operator (*): To bring all public items from a path into scope, you can use the * operator, like use std::collections::*;. However, this should be used with caution as it can make it unclear where names are coming from.

The as Keyword for Aliasing: If you have two items with the same name from different modules, you can use the as keyword to create an alias.

rust
use std::fmt::Result;
use std::io::Result as IoResult;

fn function1() -> Result {
    // ...
}

fn function2() -> IoResult<()> {
    // ...
}

By understanding and applying these concepts of packages, crates, modules, paths, and the use keyword, you can effectively manage the complexity of your growing Rust projects, keeping your code organized, readable, and maintainable. 🚀

Extra Reading:

Challenge

You are tasked with organizing the backend code for a new e-commerce platform. The initial code is a flat collection of functions and structs. Your goal is to refactor it into a well-structured library using Rust's module system.

Requirements:

  1. Create a top-level module named shop.
  2. Inside shop, create two public sub-modules: products and inventory.
  3. Move the Product struct and the add_product function into the products module. Both should be public.
  4. Move the check_stock function and the private helper function get_warehouse_location into the inventory module. check_stock must be public. The check_stock function should call its private helper get_warehouse_location.
  5. Create another public module at the top-level (a sibling to shop) named orders.
  6. Inside orders, define a public function create_order which accepts a Product and a u32 quantity. create_order must call shop::inventory::check_stock using its absolute path to verify stock before creating an order.
  7. The orders module also contains a custom Result<T> enum. In your main function, you need to use std::io::Result. To avoid a name conflict, import std::io::Result using the alias IoResult.
  8. In the main function, use the use keyword to bring the Product struct, add_product function, and create_order function into scope.
  9. Finally, in main, instantiate a Product, and then call add_product and create_order with it to demonstrate that your module structure is correct.

Expected result

Your final code should be a single block that compiles successfully. It must contain the following structure:

  • A top-level public module named shop.
  • Inside shop, two public modules: products and inventory.
    • products contains the public Product struct and add_product function.
    • inventory contains the public check_stock function and the private get_warehouse_location function.
  • A top-level public module named orders containing the public create_order function and the private Result enum.
  • The create_order function must correctly call shop::inventory::check_stock.
  • The main function must correctly use use statements to import shop::products::Product, shop::products::add_product, orders::create_order, and std::io::Result as IoResult.
  • The main function should successfully create a Product instance and pass it to both add_product and create_order.
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.