- Create a file named sample_control.rs in the project workspace.
- Write the code header with the details of the code:
//-- #########################
//-- Task: To create a sample module to illustrating `use`
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 4 March 17
//-- #########################
- Create other_function using the use keyword, in order to create the binding for the deeply module's items:
// Bind the `deeply::nested::function` path to
`other_function`.
use deeply::nested::sample_function as other_function;
- Declare the nested module deeply with the nested module named nested containing the public function sample_function:
// Defined a nested
mod deeply {
pub mod nested {
pub fn sample_function() {
println!("called `deeply::nested::function()` ")
}
}
}
- Create a function named sample_function:
fn sample_function() {
println!("called `function()` ");
}
- Declare the main function by calling other_function:
fn main() {
// Easier access to `deeply::nested::function`
other_function();
- Create a block. In this block, use the use keyword and declare deeply :: nested :: sample_function, which is equivalent to binding it to sample_function:
println!("Entering a block n");
{
// This is equivalent to `use deeply::nested::sample_function
as sample_function`.
// This `sample_function()` will shadow the outer one.
use deeply::nested::sample_function;
sample_function();
// `use` bindings have a local scope. In this case, the
// shadowing of `function()` is only in this block.
println!("Leaving the block ");
}
- Call sample_function outside the block that is created:
sample_function();
}
Upon the correct setup of the preceding code, you should get the following output when you compile and run the program: