How to do it...

  1. Create a file named sample_mod.rs and open it in your text editor.
  2. 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
//-- #########################
  1. 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()`
");
}
  1. 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()` ");
}
  1. 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();
}
}
  1. 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` ");
}
  1. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.152.58