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:

5 Structuring Rust libraries

5.1 Modules

 
 
 

5.1.1 Who cares?

 
 
 
 

5.1.2 Multiple files

 
 
 

5.2 Paths

 
 
 

5.2.1 Relative vs Absolute paths

 
 
 

5.2.2 Path Aliases

 
 
 

5.3 Upward Visibility

 
 
 

5.4 Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest