How to have multiple files with one module?

后端 未结 2 1098
一整个雨季
一整个雨季 2020-12-11 18:02

I don\'t understand why we have only one file per module.

// main.rs

mod dog; // Find dog in dog.rs or dog/mod.rs
fn main() {
    dog::sonic_bark();
}
         


        
2条回答
  •  眼角桃花
    2020-12-11 18:37

    You cannot.

    You can have more modules than files (the typical examples being mod tests nested in the file), but not the reverse.


    However, this does not matter because you can use encapsulation + re-export.

    The default when declaring a submodule with mod xxx; is that xxx is private: no user of the current module will know that it depends on xxx.

    Combine this with selecting re-exporting symbols:

    pub use self::leg::walk;
    pub use self::head::nose::smell;
    pub use self::tail::iron_tail;
    pub use self::mouth::sonic_bark;
    

    And you can call those directly: dog::walk(), dog::smell(), ...

    Therefore, private imports and public re-exports help you have a hidden internal hierarchy while exposing a flat public interface.


    Complete example:

    mod dog {
        pub use self::head::nose::smell;
        pub use self::leg::walk;
        pub use self::mouth::sonic_bark;
        pub use self::tail::iron_tail;
    
        mod leg {
            pub fn walk() {}
        }
    
        mod head {
            pub mod nose {
                pub fn smell() {}
            }
        }
    
        mod tail {
            pub fn iron_tail() {}
        }
    
        mod mouth {
            pub fn sonic_bark() {}
        }
    }
    
    fn main() {
        dog::sonic_bark();
    }
    

提交回复
热议问题