5 Structuring Rust libraries

 

This chapter covers

  • Organizing Rust code using modules
  • Understand how paths work in relation to Rust modules
  • Working with visibility rules

Virtually all programming languages have features that allow code to be divided into groups of items. So far, all the code examples that we have seen have used a flat namespace. In this chapter we will look at Rust’s powerful module system and how you can use it to structure your crates.

5.1 Modules

In Rust, a module is a container for holding items. An item is a component of a crate such as a function, struct, enum, or type (there are others, but let’s just worry about these for now). We have already used modules from the standard library when we imported the Display trait from the fmt module of the std crate. The std crate is the Rust standard library, and the fmt module contains items that help with text formatting, such as the Display and Debug traits.

Let’s imagine that we wanted to organize a small program that gets a user’s name and then says hello and goodbye to the user. Create a new Cargo project called greetings and add the following code listing to the src/main.rs file.

5.1.1 Who cares?

5.1.2 Multiple files

5.2 Paths

5.2.1 Relative vs. absolute pathspaths

5.2.2 Path aliases

5.3 Upward visibility

Summary