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:
file1.rs, file2.rs,...
that contain code we want to expose- public functions and structs are written here using the keyword
pub
at the beginning of their declaration - macros come with their
#[macro_export]
anyways, so no further changes needed
- public functions and structs are written here using the keyword
- a directory
src/folder
that contains the files from 1. - a file
src/folder.rs
that lists all files withinfolder
that we want to expose by doing:pub mod file1;
pub mod file2;
- …
- our
main.rs
(or lib.rs, depending of your app design) that references the exposed code by doing:mod folder;
- use crate::folder::file1::pub_function1
- use crate::folder::file1::pub_function2
- use crate::folder::file2::pub_function1
- use crate::folder::file2::pub_function2
- ….
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:
- src/maths/functions1.rs, src/maths/functions2.rs
- src/maths/
- src/maths.rs
- 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!