Rust modules explained

I have been playing with Rust on a pet project and when I wanted to namespace my code I got stuck for a while trying to figure out how to do it. Coming from Java and Ruby background I expected something like packages in Java or modules in Ruby but it wasn’t the case in Rust. The documentation doesn’t helped me either. It took some time for me to figure out how it works. So here is my understanding of Rust modules with simple examples(Github)

Rust requires users to build an explicit module graph

Key is every module need to be declared in root file(main.rs in this example). If you have sub modules then that need to be declared on mod.rs file of parent module.

What is mod.rs ?

You can create module in two ways either a single file or a file within folder. If you are going with later approach Rust expects the folder to have mod.rs file (File Hierarchy) which you will see later in an example.

Since I was looking for examples of these 3 use cases I thought I could add for the same

  • Single module
  • Sub modules
  • Nested modules

Single Module

If you have want to have a module in single file, well its pretty simple.

single_module.rs
main.rs

Notice that single_module has been declared in main.rs unlike some other languages where we import them.

Output:

Im in single module

Sub modules

This is a little different in Rust. My file hierarchy is

$ tree . 
.
|-- sub_modules
| |-- mod.rs
| |-- mod1.rs
| `-- mod2.rs
`-- main.rs

Note that the mod.rs here is necessary.

sub_modules/mod.rs

sub_modules/mod1.rs
sub_modules/mod2.rs

main.rs

Output:

Im in multiple module 1
Im in multiple module 2

Nested modules

Here mod_a and mod_b are going to use each other. My file hierarchy is

$ tree . 
.
|-- nested_modules
| |-- mod.rs
| |-- mod_a.rs
| `-- mod_b.rs
`-- main.rs
main.rs
nested_modules/mod.rs
nested_modules/mod_a/mod.rs
nested_modules/mod_b/mod.rs

Notice that even though mod_a and mod_b are declared in same root of hierarchy we are importing modules with use keyword.

Output:

calling mod_b from mod_a
Im in mod_b
calling mod_a from mod_b
Im in mod_a

Please write comments if you find anything incorrect, or you want to share more information about this topic.