How it works...

Using the super and self keywords, we can remove ambiguity when accessing items across modules. This can help us eliminate a lot of hardcoding of paths.

We started off by creating a function named sample_function. In all the functions, we print how the function should be called. Then, we created a module named cool with a public function named sample_function, which had the same name as that of the declared outside the scope of cool. Lastly, we created a module named sample_mod consisting of a private function named sample_function and a public nested module cool, and a public function named sample_function and publicly visible function indirect_call.

All of the action in this recipe happens in the indirect_call function, which we call from the main function by sample_mod::indirect_call(). When we start to execute the indirect_call function, it first has a print statement that prints how the function was called, and then proceeds ahead with calling self::sample_function(). The self keyword refers to the current module scope. In this case, it was sample_mod, and calling sample_function() or self::sample_function() would have given the same result as they referred to the same sample_function.

To access sample_function of other modules (which in this case is cool) inside the scope of sample_mod, we have to mention the call using the self keyword, which is self::cool::sample_function(). To call the items/units outside the scope of the sample_mod module, we use super, which basically helps in calling the items outside the scope of the current module. Here, we called sample_function using the super keyword, which fetched the function that could be accessed by any units of the code. We achieved this by calling super::sample_function(). Next, we created a block in which we had the code chunk use cool::sample_function as root_sample_function, which used the use keyword to call sample_function of the cool module outside the scope and bind the path to root_sample_function.

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

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