5 Structuring Rust libraries
This chapter covers
- Organizing Rust code using modules
Virtually all programming languages have features that allow code to be divided into groups of items.
So far all of 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 which 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, then says hello and goodbye to the user. Create a new cargo project called greetings
and add this to the src/main.rs
file: