- Create a file named sample_mod.rs and open it in your text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: To create a sample module to illustrate
how to use a module in rust
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 4 March 17
//-- #########################
- Create a module named sample_mod using the mod keyword and define a function named private_function in it:
// Defined module named `sample_mod`
mod sample_mod {
// By default all the items in module have private
visibility
fn private_function() {
println!("called `sample_mod::private_function()`
");
}
- Define a function named sample_function by marking its visibility as public, using the pub keyword in the module:
// Using the `pub` keyword changes it visibility to public
pub fn sample_function() {
println!("called `sample_mod::sample_function()` ");
}
- Declare a public function indirect_private_fn, which would call private_function:
// Public items of the module can access the private visible
items
pub fn indirect_private_fn() {
print!("called `sample_mod::indirect_access()`, that ");
private_function();
}
}
- Define sample_function outside the scope of the sample_mod module:
// Created a sample function to illustrate calling of
fn sample_function() {
println!("Called the `sample_function()` which is not a part
of
mod `sample_mod` ");
}
- Declare the main function, in which we will call each item of the sample_mod module to understand how they work and print the output:
// Execution of the program starts from here
fn main() {
// Calling the sample_function which is outside module
sample_function();
// Calling the public visible sample_mod's sample_function
sample_mod::sample_function();
// Accessing the private function indirectly
sample_mod::indirect_private_fn();
// Error! `private_function` is private
//sample_mod::private_function(); // TODO ^ Try uncommenting
this line
}
Upon the correct setup of the preceding code, you should get the following screenshot output when you compile and run the program: