Rust Modules Cheat Sheet

If you struggle as regularly with the super explicit Rust modules system as I do, then welcome to the club. For us poor souls, I decided to write down a quick cheat sheet about how to structure our modularized code.

Limitations

This post focuses on the directory and file structure only. It does not cover use, mod, crate:: et. al. in-depth. If you would like me to cover them, feel free to let me know in the comments.

The Module Setup

Consider a generic cargo new – generated project with one module we want to expose. We will have the following participating files and folders named in a very generic way here. These are listed from deep inside the project tree to higher levels:

  1. file1.rs, file2.rs,... that contain code we want to expose
    1. public functions and structs are written here using the keyword pub at the beginning of their declaration
    2. macros come with their #[macro_export] anyways, so no further changes needed
  2. a directory src/folder that contains the files from 1.
  3. a file src/folder.rs that lists all files within folder that we want to expose by doing:
    1. pub mod file1;
    2. pub mod file2;
  4. our main.rs (or lib.rs, depending of your app design) that references the exposed code by doing:
    1. mod folder;
    2. use crate::folder::file1::pub_function1
    3. use crate::folder::file1::pub_function2
    4. use crate::folder::file2::pub_function1
    5. use crate::folder::file2::pub_function2
    6. ….

Please check this bitbucket repo for an in action-demo. We will use the maths Rust module next. The macros module is a bonus for you. Here’s a quick mapping of the file and folder names according to the schema above:

  1. src/maths/functions1.rs, src/maths/functions2.rs
  2. src/maths/
  3. src/maths.rs
  4. src/main.rs

When we review those files, we will see that they do exactly, what the schema expects us to.

So far about Rust modules…

I hope this little sheet will help you to remember the complex structure of Rust modules. If you have an improvement idea, or if you found a defect, please feel free to drop it in the comments – I watch the comment sections regularly – or send me an email.

Have great day!

Home » modules
Share it with: