RustBrock/Modules and Use.md

2.8 KiB

Use

use the keyword This is used to bring paths into scope pub keyword is used to make items public as keyword for globs and external packages

Modules

Cheat Sheet

  • Start from the Root Crate: compiler starts here to look for code to compile
    • Normally src/main.rs for binary crates or src/lib.rs for library crates
  • Declaring Modules: These are declared in the crate root file
    • For example if you had a module called garden
    • it would be declared by mod garden;
    • The complier would then look in these places
      • Inline, within curly brackets that replace the semicolon following mod garden
      • In the file src/garden.rs
      • In the file _src/garden/mod.rs
  • Declaring submodules: in any other file you can declare submodules in any other file than the root
    • it would be declared by mod vegetables;
    • The complier would then look in these places for the submodule
      • Inline, directly following mod vegetables, within curly brackets instead of the semicolon
      • In the file src/garden/vegetables.rs
      • In the file _src/garden/vegetables/mod.rs
  • Paths to code in Modules: once a module is part of your crate, you can refer to the code in that module form anywhere else in that same crate as long as the privacy rules allow using that part of the code
    • Example Asparagus is a struct/type in the graden vegetables module would be found at crate::graden::vegetables::Asparagus
  • Private vs. public: code is private by default to the parent module to make it public.
    • To make a module public declare it with pub mod instead of mod.
    • To make items within the public module public as well add pub before their declaration
  • The use keyword: This is used to shorten the full path to just the last :: in the declaration
    • example use
    • crate::garden::vegetables::Asparagus
    • to now
    • use crate::garden::vegetables::Asparagus;
    • now can call this module by just Asparagus

Here is how this example's file directory would look

backyard
├── Cargo.lock
├── Cargo.toml
└── src
    ├── garden
    │   └── vegetables.rs
    ├── garden.rs
    └── main.rs

src/main.rs

use crate::garden::vegetables::Asparagus;

pub mod garden;

fn main() {
    let plant = Asparagus {};
    println!("I'm growing {plant:?}!");
}

src/garden.rs

pub mod vegetables;

src/garden/vegetables.rs

#[derive(Debug)]
pub struct Asparagus {}

used to group code together and make easier to reuse modules allow for the control of privacy, implementations needs to be declared as public otherwise it will be private by default not available to other modules if private

public modules and implementations can allow for different code to depend on it

this should be used to organize code like a file directory