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
|
|
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 likemy_mod::private_func
, but because it’s private it can only be accessed withinmy_mod
) - Line 5, We make a public (
pub
) function calledpublic_func
(it can be accessed from within or ouside themy_mod
module) - Line 8, We make a public function called
indirect_func
(this function is likepublic_func
except it demonstrates that we now have access toprivate_func
withinindirect_func
)
The
indirect_func
could be used for accessing an API method in a safe manner.
Struct Visability
|
|
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 onlymy
can access it) - Line 3, We make a public
Point
structure, it has 2 public fields (x
andy
, 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.