Modules and Packages
# CHAPTER 16
Modules and Packages
1. Chapter Introduction
Up until now, all our code has been written inside a single file:src/main.rs. In real-world projects, your code will be split across dozens of files and folders (e.g., authentication, database, routing). Rust has a unique and strict module system to manage code organization and visibility. In this chapter, we will learn how to split code into multiple files, use the pub keyword, and install third-party libraries (Crates) using Cargo.
2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the difference between a Package, Crate, and Module.
- Create inline modules.
- Split code into multiple files and folders.
-
Use the
pubkeyword to manage privacy (Encapsulation).
-
Install and use third-party crates from
crates.io.
3. Packages, Crates, and Modules
Rust has specific terminology for organization:-
1.
Package: What you create when you type
cargo new. It contains aCargo.tomlfile.
-
2.
Crate: A tree of modules that produces an executable binary or a library. (e.g.,
main.rsis the "crate root" for a binary crate).
- 3. Module: A way to organize code within a Crate into named, nested blocks.
4. Creating Inline Modules and Privacy
By default, everything in Rust (functions, structs, fields) is Private. If you create a module, code outside that module cannot see inside it unless you use thepub (public) keyword.
5. Splitting Code into Multiple Files
Inline modules get messy. Let's move thenetwork code into its own file!
1. Update src/main.rs:
Tell Rust to look for a file or folder named network.
2. Create a new file src/network.rs:
6. The use Keyword
Typing long paths like std::collections::HashMap every time is tedious. The use keyword brings a path into the current scope, so you can call it directly.
7. Third-Party Crates (Cargo.toml)
Rust's standard library is intentionally kept small. For things like Random Number Generation or Web Servers, you download Crates from the official registry: crates.io.
To use an external crate, you add it to your Cargo.toml file under [dependencies].
You can do this manually, or by using the terminal:
Now, you can use it in your code!
8. Common Mistakes
-
Forgetting
pubon Struct Fields: If you make a struct public (pub struct User), its *fields* are still private by default! You must explicitly mark the fields you want to expose:pub email: String.
-
Using
modin the wrong place: Beginners often putmod network;insidenetwork.rs. You only declaremodin the parent file (usuallymain.rsorlib.rs) to build the module tree.
9. Best Practices
-
Organize by Domain: Group your files by feature (e.g.,
mod auth;,mod database;).
-
Use absolute paths for clarity: When bringing things into scope, prefer absolute paths starting with
crate::(e.g.,use crate::network::connect;).
10. Exercises
- 1. Create a new Cargo project.
-
2.
Create a new file
math.rscontaining apub fn add(a: i32, b: i32) -> i32.
-
3.
In
main.rs, declaremod math;and call theaddfunction. Print the result.
11. MCQs with Answers
What is the default visibility of functions and structs in Rust?
Which keyword exposes a function or struct to code outside its module?
If src/main.rs contains mod utils;, what file is the Rust compiler looking for?
utils.rs in mod utils {}?
a) Yes b) No, the file itself inherently acts as the module body.
Answer: b) No.
What keyword is used to bring a module path into the current scope to avoid typing long names?
What is the central registry for open-source Rust libraries?
In which file do you list the third-party crates your project depends on?
What terminal command automatically downloads and adds a dependency to your Cargo.toml?
pub struct User { name: String }, can another module access the name field?
a) Yes b) No, because the fields inside the struct are still private by default. You must declare it as pub name: String.
Answer: b) No, fields are private by default.
What is a "Crate" in Rust?
12. Interview Questions
-
Q: Explain Rust's module system and how the
modkeyword differs from theimportorrequirekeywords in other languages. (Answer:modbuilds the module tree and tells the compiler what files to include;usemerely creates a shortcut path).
- Q: How does Rust handle Encapsulation (Access Modifiers)?
13. Summary
Organizing code effectively is crucial for building large applications. Rust's module system enforces strict privacy boundaries, requiring you to deliberately expose APIs usingpub. With the power of Cargo and crates.io, integrating complex third-party tools into your clean module architecture takes only seconds.