A module is a colletction of items:
- functions
- structs
- traits
impl
blocks- other modules
features
Split code in logical units(modules), manage visibility(public/private) between them.
Visibility
By default, the items in a module have private visibility, but this can be overridden with pub
. Only the public items of a module can be accessed from outside the module scope.
1 | mod my_mod { |
Public items, including those inside nested modules, can be accessed from outside the parent module.
1 | fn main() { |
pub(crate)
Functions declared using pub(crate)
syntax are only visible within the current crate.
1 | mod my_mod { |
pub(crate)
can be called from anywhere in the same module.
pub(in path)
Functions declared by pub(in path)
syntax are only visible within the given path. path
must be a parent or ancestor module.
1 | mod my_mod { |
pub(crate)
items can only be called from within the module specified.
1 | fn main() { |
pub(self)
Functions declared by pub(self)
syntax are only visible within the current module, which is same as leaving them private.
pub(super)
Functions declared using pub(super)
syntax are only visible within the parent module.
private module
Nested modules follow the same rules for visibility.
1 | my_mod { |
struct visibility
Structs have an extra level of visibility with their fields. The visibility defaults to private, and can be overridden with pub
modifier.
use
and as
The use
declaration can be used to bind a full path to a new name, and the as
keywords can bind imports to a different name.
1 | use xxx::yyy::function1; |
super
and self
The super
keyword refers to the parent scope, the self
keyword refers to the current module scope - in the following case mod1
. Note we can use self
to access another module inside mod1
(in this case mod2
).
1 | fn f() { |
File heirarchy
Modules can be mapped to a file/directory.
For example:
1 | . |
main.rs:
1 | mod my_mod; |
Note the mod my_mod
, this declaration will look for a file named my_mod.rs
or my_mod/mod.rs
and will insert its contents inside a module named my_mod
under this scope.
mod.rs:
1 | pub mod nested_mod; |
Same as before. pub mod nested_mod;
will locate the nested_mod.rs
and insert it here under their respective modules. Note it follows the same rules for visibility. For instance, if we remove pub
from pub mod nested_mod
, we couldn’t call my_mod::nested_mod::function();
in main.rs
.