Modules

In Rust, a Module is used to control visibility, and used to gather structs, impl blocks, functions and methods together into a single Module.

Visability

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
mod my_mod {
    fn private_func() {
        println!("my_mod::private_function() Can only be called from within the module.");
    }
    pub public_func() {
        println!("my_mod::public_function() Can be called from within and outside the module.");
    }
    pub indirect_func() {
        println!("my_mod::indirect_function() Can be called from within and ouside the module,");
        println!("but it also calls...");
        private_func();
    }
}

To explain some of the above.

  • Line 1, We make a mod called my_mod.
  • Line 2, We make a private function called private_func (access would look like my_mod::private_func, but because it’s private it can only be accessed within my_mod)
  • Line 5, We make a public (pub) function called public_func (it can be accessed from within or ouside the my_mod module)
  • Line 8, We make a public function called indirect_func (this function is like public_func except it demonstrates that we now have access to private_func within indirect_func)

The indirect_func could be used for accessing an API method in a safe manner.

Struct Visability

1
2
3
4
5
6
7
mod my {
    struct Privatepoint(i32, i32)
    pub struct Point {
        pub x: i32,
        pub y: i32
    }
}

To expalin the above:

  • Line 1, We make a mod called my
  • Line 2, We make a private structure called Privatepoint which is a tuple-like structure (It’s private so only my can access it)
  • Line 3, We make a public Point structure, it has 2 public fields (x and y, both signed 32-bit integers (i32))

We can access Point and Point’s x and y fields, but we can’t access Privatepoint from outside my module.