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;
  4. fn function() {
  5. println!("called `function()`");
  6. }
  7. fn main() {
  8. my::function();
  9. function();
  10. my::indirect_access();
  11. my::nested::function();
  12. }

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;
  6. pub fn function() {
  7. println!("called `my::function()`");
  8. }
  9. fn private_function() {
  10. println!("called `my::private_function()`");
  11. }
  12. pub fn indirect_access() {
  13. print!("called `my::indirect_access()`, that\n> ");
  14. private_function();
  15. }

In my/nested.rs:

  1. pub fn function() {
  2. println!("called `my::nested::function()`");
  3. }
  4. #[allow(dead_code)]
  5. fn private_function() {
  6. println!("called `my::nested::private_function()`");
  7. }

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()`