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
rustc
is considered a crate. Crates can come in 2 forms:
- Binary Crate
- Programs you can compile into a runnable executable
- Must have a function called
main
that defines when executable rungs
- Library Crate
- Define functionality intended to be shared with multiple projects
rand
crate provides functionality to generate random numbers.- Generally
Crate
means 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.toml
that describes how to build those crates. lib.rs
is the root of a library cratemain.rs
is 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.rs
src/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.rs
src/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:
Asparagus
type 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
pub
to make singular items public as well.
‘Use’ Keyword
use
keyword creates shortcuts to items to reduce paths.
- Example:
crate::garden::vegetables::Asparagus
use crate::garden::vegetables::Asparagus
- Now only need to write Asparagus
backyard
├── Cargo.lock
├── Cargo.toml
└── src
├── garden
│ └── vegetables.rs
├── garden.rs
└── main.rs
Library 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_payment
Using Super:
fn deliver_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::deliver_order();
}
fn cook_order() {}
}