File hierarchy

Modules can be mapped to a file/directory hierarchy. Let’s break down the visibility example in files:

1. $ tree .
2. .
3. |-- my
4. |   |-- inaccessible.rs
5. |   |-- mod.rs
6. |   `-- nested.rs
7. `-- split.rs

In split.rs:

1. // This declaration will look for a file named `my.rs` or `my/mod.rs` and will
2. // insert its contents inside a module named `my` under this scope
3. mod my;

5. fn function() {
6. println!("called `function()`");
7. }

9. fn main() {
10. my::function();

12. function();

14. my::indirect_access();

16. my::nested::function();
17. }

In my/mod.rs:

1. // Similarly `mod inaccessible` and `mod nested` will locate the `nested.rs`
2. // and `inaccessible.rs` files and insert them here under their respective
3. // modules
4. mod inaccessible;
5. pub mod nested;

7. pub fn function() {
8. println!("called `my::function()`");
9. }

11. fn private_function() {
12. println!("called `my::private_function()`");
13. }

15. pub fn indirect_access() {
16. print!("called `my::indirect_access()`, that\n> ");

18. private_function();
19. }

In my/nested.rs:

1. pub fn function() {
2. println!("called `my::nested::function()`");
3. }

5. #[allow(dead_code)]
6. fn private_function() {
7. println!("called `my::nested::private_function()`");
8. }

In my/inaccessible.rs:

1. #[allow(dead_code)]
2. pub fn public_function() {
3. println!("called `my::inaccessible::public_function()`");
4. }

Let’s check that things still work as before:

1. $ rustc split.rs && ./split
2. called `my::function()`
3. called `function()`
4. called `my::indirect_access()`, that
5. > called `my::private_function()`
6. called `my::nested::function()`