Rust modules

From wikinotes
Revision as of 01:50, 8 February 2023 by Will (talk | contribs)

Modules are rust libraries.
The std::prelude module is included in the scope of every program.

Entrypoint

For modules to be compiled, they must be used (however indirectly)
from either your crate's main.rs or lib.rs.

Naming/Paths

Module names govern where they can be found within the filesystem.
Module locations are based on where they are defined

# from the rust book:
backyard
├── Cargo.lock
├── Cargo.toml
└── src
    ├── garden
    │   └── vegetables.rs
    ├── garden.rs
    └── main.rs

The module foo's code could be

  • src/foo.rs
  • src/foo/mod.rs

Imports

use std::io;        // merges objects from namespace into your own
use std::fs::File;  // merge 'File' only into current namespace

std::io::stdin()    // you also can access objects from their namespace

Access Control

By default, a module's code is public to itself and it's children,
but private to it's parents and/or callers.

pub mod house {
    pub mod livingroom {
        // ...
    }
    mod bedroom {
        // ...
    }
}