Rust provides a powerful module system that can be used to hierarchically split code in logical units (modules), and manage visibility (public/private) between them.
A module is a collection of items: functions, structs, traits,
implblocks, and even other modules.
By default, the items in a module have private visibility, but this can be overridden with the pub
modifier. Modules can also be nested (anidados).
mod mi_mod{
//structs
//funciones
//pueden ser pub o privadas al main!
}
fn main(){
...
mi_mod::funcion() //asi lo uso en el main
}
Ver ejemplo:
The usedeclaration can be used to bind a full path to a new name, for easier access.
// Bind the `deeply::nested::function` path to `other_function`.
use deeply::nested::function as other_function;
mod deeply {
pub mod nested {
pub fn function() {
println!("called `deeply::nested::function()`");
}
}
}
fn main() {
// Easier access to `deeply::nested::function`
other_function();
}
The superand selfkeywords can be used in the path to remove ambiguity when accessing items and to prevent unnecessary hardcoding of paths.
fn function() { //es la que dsp se llama con super::function()
println!("called `function()`");
}
mod cool {
pub fn function() { //la que se llama root_function más abajo
println!("called `cool::function()`");
}
}
mod my {
fn function() {
println!("called `my::function()`");
}
mod cool {
pub fn function() {
println!("called `my::cool::function()`");
}
}
pub fn indirect_call() {
// Let's access all the functions named `function` from this scope!
print!("called `my::indirect_call()`, that\\n> ");
// The `self` keyword refers to the current module scope - in this case `my`.
// Calling `self::function()` and calling `function()` directly both give
// the same result, because they refer to the same function.
self::function();
function();
// We can also use `self` to access another module inside `my`:
self::cool::function();
// The `super` keyword refers to the parent scope (outside the `my` module).
super::function();
// This will bind to the `cool::function` in the *crate* scope.
// In this case the crate scope is the outermost scope.
{
use crate::cool::function as root_function;
root_function();
}
}
}
fn main() {
my::indirect_call();
}