← Back to Rust Course | Chapter 15: Cargo, Testing & Best Practices | Lesson 2 of 8

Using Crates from crates.io

crates.io is a big public shelf of ready-made Rust code that anyone can add to their own project.

What crates.io Is

crates.io is the central, official registry where the Rust community publishes reusable packages, called crates, that any project can depend on via Cargo.

Example: What crates.io Is

markup
fn main() {
    println!("crates.io hosts community packages like serde, rand, and clap");
}

Adding a Dependency Manually

To use a crate from crates.io, you add an entry under [dependencies] in Cargo.toml specifying its name and version requirement.

Example: Adding a Dependency Manually

bash
[dependencies]
rand = "0.8"

⚠️ Run this command in your terminal.

Using cargo add

The cargo add subcommand automatically finds the latest compatible version of a crate and adds it to Cargo.toml for you, without manual editing.

Example: Using cargo add

bash
cargo add rand

⚠️ Run this command in your terminal.

Standard Library Only in This Course

Because sandboxed code runners (including the one running these examples) often lack network access to fetch crates, every runnable example in this course intentionally uses only the Rust standard library.

Example: Standard Library Only in This Course

markup
fn main() {
    println!("This course sticks to the standard library so every example can run offline");
}
Common Mistakes
  1. Assuming a crate is added to your project automatically just by writing use in your code -- it must be declared in Cargo.toml first.
  2. Adding a crate without checking its version compatibility, which can pull in breaking changes unexpectedly.
  3. Forgetting Judge0-style sandboxes without network access cannot download crates, so exercises there must rely on the standard library only.
Chapter Summary
  • crates.io is the official public registry for Rust packages (crates).
  • Adding a crate as a [dependencies] entry in Cargo.toml makes it available to use in your code.
  • cargo add crate_name is a convenient way to add a dependency without manually editing Cargo.toml.
  • Popular crates like serde (serialization) and rand (random numbers) extend what the standard library alone can do.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.