Rust Modules

controlling visibility with pub

Making a functioning public

The function is made available to external functions by using the “pub” keyword at the beginning of the declaration.

Following are the privacy rules:

  • Any of the parent modules can access a function or module that is public.
  • Any function or module that is marked as private can be accessible by both the parent module and its immediate child module.

Example:

				
					mod outer  
{  
   pub fn a()  
   {  
     println!("function a");          
   }  
   fn b()  
   {  
      println!("function b");  
   }  
   
mod inner  
{  
  pub fn c()  
  {  
    println!("function c");  
  }  
  fn d()  
  {  
    println!("function d");  
  }  
}  
}  
fn main()  
{  
  outer::a();  
  outer::b();  
  outer::inner::c();  
  outer::inner::d();  
}  
				
			

Output:

controlling visibility with pub -

The main() method in the example above represents the root module, but the current root module of our project is an outer module. Consequently, the outer module is accessible to the main() method.

Since the function a() is public, calling outer::a() won’t result in any errors. However, since outer::b() is a private function, the main() method will encounter compilation errors when attempting to access it.

The inner module is private, thus the main() function cannot access it. An inner module can only be accessed by its parent module, or outer module, since it does not have any children.

Share this Doc

controlling visibility with pub

Or copy link

Explore Topic