Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
modules
functions

Modules in Rust

Anusheh Zohair Mustafeez

In Rust, modules are containers that enclose zero or more items (i.e., functions, structs, traits, impl blocks, and nested modules). These containers help to hierarchically organize code into logical units and then govern those units’ scope.

svg viewer

Code

The mod keyword is used to define a module item. By default, any item inside a module is private, so it cannot be accessed from outside that module. The pub keyword can be used to change this and give that item public visibility. The code below shows how we can use these keywords:

mod external_mod {
    
    pub fn public_func() {
        println!("Public function called\n");
    }

    fn private_func(){
        println!("Private function called\n");
    }
    
    pub fn private_func_accessor() {
        println!("Accessing private function with a public function");
        private_func();
    }

    mod internal_mod {
        pub fn public_internal_func() {
            println!("Public function inside internal mod called\n");
        } 
    }

    pub fn internal_mod_accessor() {
        println!("Accessing internal mod with a public function");
        internal_mod::public_internal_func();
    }
}

fn main() {
    external_mod::public_func();

    external_mod::private_func_accessor();

    external_mod::internal_mod_accessor();
}

RELATED TAGS

rust
modules
functions

CONTRIBUTOR

Anusheh Zohair Mustafeez
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring