How it works...

In this recipe, you learned how to create a sample module in Rust and how you are allowed to call the items of the module.

From this chapter onward we will follow the header style, which is our first step. It basically describes what the code or part of the application unit does. This is a very good code practice to follow, as it helps when another person starts off from where you develop.

We created a module named sample_mod using the mod keyword, followed by the braces {}. The content of the module is its items. Each item is designed to perform a specific task. By default, all the items in the module have private visibility, which means that they cannot be accessed directly outside the scope. In the sample_mod module, we explicitly created two functions with public visibility using the pub keyword. We added the keyword before creating or declaring the function using the fn keyword. This makes the item publicly visible outside the scope of the module. The private function or items can be accessed inside the scope of the module, where all the items can call each other, so we can indirectly call a public item to access a private item from it.

We create four functions in this code, where three are inside the module and one is accessible globally. The first function we created inside sample_mod was private_function, which, by default, has private visibility. Then we created two public functions, namely sample_function and indirect_private_fn, where indirect_private_fn calls private_function in its body.

To call an item of the module outside its scope, we have to follow a particular syntax--module_name::publically_visible_function name. In the main function, we call sample_fucntion, which is a regular function, and the two publicly visible items of the sample_mode module: function sample_mod::sample_function() and sample_mod::indirect_private_fn(). These items will execute the content inside their respective scope.

On calling the private item of the module, it will throw an error saying that the particular item is private. For example, in the preceding recipe, we got an error when we directly called sample_mod::private_function(); from the main function.
..................Content has been hidden....................

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