Using Crates from crates.io
In this page:
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
fn main() {
println!("crates.io hosts community packages like serde, rand, and clap");
}
Login to try C/C++/Java/PHP code in the editor
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
[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
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
fn main() {
println!("This course sticks to the standard library so every example can run offline");
}
Login to try C/C++/Java/PHP code in the editor
- Assuming a crate is added to your project automatically just by writing
usein your code -- it must be declared inCargo.tomlfirst. - Adding a crate without checking its version compatibility, which can pull in breaking changes unexpectedly.
- Forgetting Judge0-style sandboxes without network access cannot download crates, so exercises there must rely on the standard library only.
- crates.io is the official public registry for Rust packages (crates).
- Adding a crate as a
[dependencies]entry inCargo.tomlmakes it available tousein your code. cargo add crate_nameis a convenient way to add a dependency without manually editingCargo.toml.- Popular crates like
serde(serialization) andrand(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: