As code grows, can be split into modules and multiple files.
Package:
- Can contain multiple binary crates
- Optionally 1 library crate
Package: Cargo feature that lets you build, test, and share crates. Crates: Tree of modules that produces a library or executable Modules and use: Let you control the organization, scope, and privacy of paths. Paths: Way of naming a item, such as struct, function, or module
Packages and Crates
Crates
Crate: Smallest amount of code the Rust compiler considers in a runtime.
- Compiling a single file with
rustcis considered a crate. Crates can come in 2 forms:
- Binary Crate
- Programs you can compile into a runnable executable
- Must have a function called
mainthat defines when executable rungs
- Library Crate
- Define functionality intended to be shared with multiple projects
randcrate provides functionality to generate random numbers.- Generally
Cratemeans library crate. Crate Root - File that the Rust compiler starts from and makes up root module of your crate.
Package
- Bundle of 1 or more crates that provides a set of functionality.
- Contains a
Cargo.tomlthat describes how to build those crates. lib.rsis the root of a library cratemain.rsis the root of a binary crate
Defining Modules to Control Scope and Privacy
Declaring Modules
- In crate root you can declare new modules.
- Say you declare a garden module
mod garden;compiler will look in:src/garden.rssrc/garden/mod.rs
Declaring Submodules
- In any file other than crate root, you can declare submodules.
- Example,
mod vegetables;in src/garden.rs, compiler will look in:src/garden/vegetables.rssrc/garden/vegetables/mod.rs
Paths to code in modules
Once a module is a part of your crate, code can be referred to anywhere else in crate, as long as privacy rules allows.
- Example:
Asparagustype in garden vegetables module:crate::garden::vegetables::Asparagus
Private vs. Public
- Code within a module is private from it’s parent modules by default.
- To make module public declare it with
pub mod - Use
pubto make singular items public as well.
‘Use’ Keyword
use keyword creates shortcuts to items to reduce paths.
- Example:
crate::garden::vegetables::Asparagususe crate::garden::vegetables::Asparagus- Now only need to write Asparagus
backyard
├── Cargo.lock
├── Cargo.toml
└── src
├── garden
│ └── vegetables.rs
├── garden.rs
└── main.rsLibrary Module Example
Modules can be used to control privacy of items. Modules are private by default.
Restaurant
mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn serve_order() {}
fn take_payment() {}
}
}crate // module tree not file system tree
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_paymentUsing Super:
fn deliver_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::deliver_order();
}
fn cook_order() {}
}