- Create a file named sample_access.rs in the project workspace.
- Write the code header with the details of the code:
//-- #########################
//-- Task: To create a sample module to illustrating `self` and
`super`
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 4 March 17
//-- #########################
- Create a function named sample_function and print "called `sample_function()`" in its scope:
fn sample_function() {
println!("called `sample_function()`");
}
- Declare a module named cool using the mod keyword and create a function named sample_function with public visibility. Then, print called `cool::sample_function()` n in its scope:
// Ddefined a module names cool
mod cool {
pub fn sample_function() {
println!("called `cool::sample_function()` ");
}
}
- Create another module using the mod keyword named sample_mod and create a function item named sample_function by printing "called `sample_mod::sample_function()` n":
mod sample_mod {
fn sample_function() {
println!("called `sample_mod::sample_function()` ");
}
- Create a module named cool with the function item sample_function by marking its visibility as public using the pub keyword, and printing "called `sample_mod::cool::sample_function()` n":
mod cool {
pub fn sample_function() {
println!("called `sample_mod::cool::sample_function()`
");
}
}
- Create another function inside the cool module named indirect_call by marking its visibility as public using the pub keyword, and printing "called `sample_mod::indirect_call()`, thatn> ":
pub fn indirect_call() {
// Let's access all the sample_functions named
`sample_function` from
this scope!
print!("called `sample_mod::indirect_call()`, that > ");
Call sample_function using the self and super keywords:
// The `self` keyword refers to the current module scope - in
this case
`sample_mod`.
// Calling `self::sample_function()` and calling
`sample_function()`
directly both give
// the same result, because they refer to the same
sample_function.
self::sample_function();
sample_function();
// We can also use `self` to access another module inside
`sample_mod`:
self::cool::sample_function();
// The `super` keyword refers to the parent scope (outside the
`sample_mod` module).
super::sample_function();
- Create a block and call root_sample_function, which is bound to cool::sample_function:
// This will bind to the `cool::sample_function` in the *crate*
scope.
// In this case the crate scope is the outermost scope.
{
use cool::sample_function as root_sample_function;
root_sample_function();
}
}
}
- Define the main function and call the sample module's indirect_call function:
// Execution starts here
fn main() {
// Calling the sample_mod module's item
sample_mod::indirect_call();
}
Upon the correct setup of the preceding code, you should get the following screenshot as output when you compile and run the program: