Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Module defined in the main.rs file

  • mod

  • pub

  • In order to divide our code into logical units we can use modules.

  • First step is to define a module using the mod keyword in the main.rs file and inside the module we can define functions, structs, enums etc.

  • However, in order to be able to call the function from the code outside of the module, we need to make the function public using the pub keyword.

  • We can access the public function in two different ways.

fn main() {
    println!("in main");

    // crate::tools::private_helper(); // private function

    tools::public_helper();
    crate::tools::public_helper();
}

mod tools {
    fn private_helper() {
        println!("in tools::private_helper");
    }

    pub fn public_helper() {
        println!("in tools::public_helper");

        private_helper();
    }
}
in main
in tools::public_helper
in tools::private_helper
in tools::public_helper
in tools::private_helper