Open In App

Rust – Module Visibility

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of module visibility. Rust is basically a systems programming language that deals with ensuring safe code proper memory management and multi-threading. By module visibility, we mean that whatever items that are present in the module are defined as privately visible, then those items can be overridden using the ‘pub’ modifier in Rust. The items declared public is accessible by outside module scope items.

One thing that must be kept in mind while dealing with module visibility is the scope of items as items are only visible only within certainly given scope only. ‘Pub’ generally makes items visible in the given path or in a given crate or in given modules also.

Example 1: 

Rust
// Calling a Public function within a Module in Rust
#[allow(dead_code)]
mod geeks_for_geeks {
    fn pvt_gfg_func() {
        println!(" calling `GFG::private_function()`");
    }
    pub fn function_one() {
        println!("  calling `geeks_for_geeks`::function_one()`");
    }
}
fn main() {
   geeks_for_geeks::function_one();   
}

Output:

Explanation:

In this example, we have declared a module geeks_for_geeks and then defined another function in its named pvt_gfg_func. Here, whatever items are present in the modules are by default privately visible. Next, we use the `pub` modifier named fn function_one so that the default visibility of the function is overridden. In the main function, we have called the module and the corresponding function using the syntax  module::function(). (here, that is geeks_for_geeks::function_one())

Example 2: 

Rust
// Indirectly accessing Functions within a Module in Rust
#[allow(dead_code)]
mod geeks_for_geeks {
    fn pvt_gfg_func() {
        println!(" calling `GFG::private_function()`");
    }
     pub fn gfg_indirect_access() {
        println!("calling `geeks_for_geeks::gfg_indirect_access()`");
        pvt_gfg_func();
    }
}
fn main() {
   geeks_for_geeks::gfg_indirect_access();
}

Output:

Explanation: 

In this example, we have continued from example 1. We have added a new function named gfg_indirect_access. This function is able to access other items when it is in the same module (Here, it is geeks_for_geeks). Next, we print a statement (as shown in the output), and then we call the pvt_gfg_func() here. In the main function we are calling the module and the function geeks_for_geeks(module)::gfg_indirect_access().


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads