Dividing Your Code Into Modules

Hands-on Rust — by Herbert Wolverson (43 / 120)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 5 Build a Dungeon Crawler | TOC | Organizing Your Imports With a Prelude 👉

You can write huge programs in one file, but dividing your code into smaller sections — known as modules in Rust — offers significant advantages:

  • It’s a lot easier to find your Map functionality in a file named map.rs than it is to remember that it’s somewhere around line 500 of an ever-growing main.rs.
  • Cargo can compile modules concurrently, leading to much better compilation times.
  • Bugs are easier to find in self-contained code that limits linkages to other sections of code.

Modules may either be a single rs file or a directory. In this chapter, you’ll use single file modules. You’ll learn to create directory-based modules in Multi-File Modules.

Crates and Modules

Rust programs are divided into crates and modules. Crates are large groups of code with their own Cargo.toml file. Your game is a crate. So is bracket-lib — every dependency you specify in Cargo is a crate. Crates are mainly independent of one another, but may each have dependencies upon other crates — and use code from them. A module is a section of code within a crate, identified by being in a separate file or directory. You can make your game code easier to navigate by grouping related code — e.g., placing all map-related code inside a…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.