【轉】Modules in Rust

原文:https://www.educative.io/edpresso/modules-in-rust

---------------------------

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();
}

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章