Packages & Crates
Imagine a desk drawer crammed with everything you own. π If itβs all in one big pile, itβs nearly impossible to find the one thing you need. But if you sort things into labeled boxes, and line those boxes up on a shelf, suddenly everything is easy to find.
Rust likes things tidy too. As your programs grow bigger, Rust gives you neat ways to organize your code so it never turns into a giant messy pile. Letβs meet the boxes and the shelves of Rust. π¦
A crate is a labeled box
A crate is one bundle of Rust code. Itβs like a single labeled box that holds related things together.
There are two kinds of crates, and they have different jobs:
- π A binary crate is one you can run. It has a special starting spot called
main. When you press Run, the computer looks formainand begins there. - π A library crate doesnβt run by itself. Instead, it holds helpful code that other crates can borrow and use, like a shelf of tools everyone shares.
main function, it can run.
If it doesn't, it's a library waiting to share its code with anyone who needs it. π¦
A package is a shelf of boxes
A package is bigger than a crate. A package is one or more crates kept together,
plus a special little list called Cargo.toml.
So the picture looks like this:
- The shelf is your package.
- The boxes on the shelf are your crates.
- The label on the shelf is
Cargo.toml.
Cargo.toml (a shelf with a label). Binary crates
run; library crates share.
Quick quiz
Which kind of crate can you run because it has a main?
Yes! A binary crate has main, so the computer knows where to start running. π
Cargo.toml label, binary crates run and
library crates share. Next up: splitting a crate into rooms with
Modules! πͺ