Namespacing With Modules

    Namespacing in C++ is completely optional which means some code may use nest namespaces while other code may be content to cover its entire codebase with a single namespace. Some code might even put its code into the global namespace. Other code might control the use of namespaces with macros.

    The equivalent to a namespace in Rust is a module and serves a similar purpose. Unlike C++ though you get namespacing automatically from the structure of your files. Each file is a module in its own right.

    So if we may have a file myapp.rs

    1. pub const SOME_VALUE: i32 = 20;
    2. pub fn doSomething(value: i32) { /* ... */ }

    Everything in myapp.rs is automatically a module called myapp. That means modules are implicit and you don’t have to do anything except name your file something meaningful.

    You could also just bring in the whole of the mod if you like:

    1. use myapp::*;
    2. doSomething(SOME_VALUE);

    But if you want an explicit module you may also write it in the code. So perhaps myapp doesn’t justify being a separate file.

    1. // main.rs
    2. pub fn error() { /* ... */ }
    3. pub fn doSomething(value: i32) { /* ... */ }
    4. }

    Modules can be nested so a combination of implicit modules (from file names) and explicit modules can be used together.

    Namespacing with modules is pretty easy, But sometimes you might have lots of files in a module and you don’t want the outside world to see a single module namespace.

    In these cases you’re more likely to use the myapp/mod.rs form. In this instance the mod.rs file may pull

    in subordinate files

    However the module also says pub use helpers::Helper which allows the outside to reference myapp::Helper. Thus a module can act as a gatekeeper to the things it references, keeping them private or selectively making parts public.

    We haven’t mentioned the other module here tests. The attribute indicates it is only pulled in when a unit test executable is being built. The cfg attribute is used for .

    Modules can be used once they are defined.

    1. use helpers::*;

    Note that the use command is relative to the toplevel main or lib module. So if you declare a mod helpers at the top, then the corresponding use helpers will retrieve it. You can also use relative use commands with the super and keywords.

    // TODOs

    TODO