Cargo Tricks & Crates.io
Imagine youβre building something, and instead of making every single piece yourself, you could reuse ready-made pieces that other people have already built and shared. Thatβs one of the best parts of Rust. π
When someone writes helpful Rust code, they can package it up and share it with the whole world. Each little package of shareable code is called a crate. π¦
Borrowing code with Cargo.toml
Every Rust project has a special file called Cargo.toml. Itβs like a shopping
list that tells Cargo (your project helper) which crates you want to use.
To add a crate, you write its name and version under [dependencies]. Hereβs how
youβd add a popular crate called rand that makes random numbers:
[dependencies]
rand = "0.8"
The next time you build, Cargo goes and fetches that crate for you, then snaps it into your project. You didnβt have to write the random-number code yourself. π²
Crates.io: the app store for code
Where do all these crates live? On a giant website called crates.io. Itβs like an app store, but instead of apps for your phone, itβs full of free code pieces for your Rust projects.
When your program is finished and you want it to run super fast, you can build a speedy version with one command:
cargo build --release
The --release part tells Cargo to spend extra time polishing your program so it
runs as quickly as possible. β‘
[dependencies]
line that adds a make-believe crate called jokes = "1.0". Now you
know exactly what real Rust programmers type!
You can share too!
The best part? One day you can publish your very own crate to crates.io so other people all around the world can use your code. You might build something that helps thousands of programmers. π
Cargo.toml, and they all live on
crates.io β the app store for code.
Quick quiz
What is crates.io?
Exactly! crates.io is full of free crates you can borrow, and one day you can share your own there too. π
Cargo.toml, crates.io is
the app store for code, and cargo build --release makes a high-speed
version. You can even publish your own crate someday. Next up: we'll put everything
together and build a real project from start to finish! π οΈ