Sub topic 1
What crates.io and Cargo Do for Your Project
Prerequisites
This chapter assumes you can do the following:
- Rust and Cargo are installed, and
cargo --versionprints a version. - You can write basic Rust code and know what a module is.
- You can create a project with
cargo newand run commands in a terminal. - You have a network connection for the commands in the walkthrough.
You don't need to know how to write a Cargo.toml dependency entry yet. The next chapters cover that.
The problem dependencies solve
Most real programs need code that you didn't write: JSON parsing, HTTP clients, random numbers, command-line argument handling. Writing all of it yourself is slow and error-prone. Copying source files into your repository is also a poor fix. You lose track of where the code came from, you miss upstream bug fixes, and two libraries that need the same helper can end up with conflicting copies.
Rust solves this with two pieces that work together:
- crates.io is the public place where Rust libraries are published and downloaded from.
- Cargo is the tool on your machine that reads your list of needed libraries, fetches them, builds them, and links them into your program.
This chapter explains what each piece does and how they fit together. Later chapters cover the details of version requirements, lockfiles, and features.
Vocabulary: package, crate, registry
Rust documentation uses a few terms that sound alike. Keep them straight from the start, because error messages use them precisely.
| Term | Meaning |
|---|---|
| Crate | The unit the compiler (`rustc`) builds. It is either a binary (has `main`) or a library. |
| Package | What Cargo manages. A package has one `Cargo.toml` and contains one or more crates. |
| Registry | A server that stores published packages and an index describing them. crates.io is the default registry. |
| Dependency | A package your package needs. Cargo builds it first and makes its library crate available to your code. |
| Manifest | The `Cargo.toml` file. It describes the package and lists its dependencies. |
In everyday speech, people say "crate" for both crates and packages, and "the serde crate" is understood. The difference matters when a package contains several crates. For example, a package can have a library and a binary that share a name.
What crates.io does
crates.io is the default package registry for the Rust community. It does three jobs.
- Hosts published packages. Each release is a compressed archive with a
.crateextension. It contains the source code and the package'sCargo.toml. Crates.io does not host prebuilt binaries for libraries. Your machine compiles dependencies from source. - Maintains an index. The index is metadata: for every package, every published version, which dependencies that version declares, which features it offers, and whether it is yanked. Cargo reads the index to decide which versions to use. By default, Cargo uses the sparse protocol, which fetches only the index files for the packages your project needs, over HTTPS.
- Keeps published versions stable. Once a version is published, its contents cannot change. An author who finds a serious problem can yank that version. A yanked version stays downloadable for projects that already depend on it, so their builds still work, but Cargo won't choose it for new resolutions. This is why a build that worked last year still works today.
crates.io also provides package names, which are first-come, first-served. The names serde and serde_json identify specific packages. The site's documentation links (docs.rs builds and hosts API documentation for every published crate), download counts, and repository links help you decide whether a crate is worth using. The chapter on evaluating crates returns to this.
What Cargo does
Cargo is a build tool, a package manager, and the command-line front end to rustc. For dependencies it does the following:
- Reads the manifest. It collects the dependencies you declared in
Cargo.toml. - Resolves versions. It looks up each dependency in the index, then looks at the dependencies those packages declare, and so on. It picks one set of versions that satisfies every requirement. If a
Cargo.lockfile already exists, Cargo reuses the versions recorded there. - Records the result. It writes the chosen versions to
Cargo.lock. - Downloads sources. It fetches each needed
.cratearchive and unpacks it into a local cache. - Compiles in order. It builds dependencies before the packages that use them, then builds your package and links everything together.
If every needed package is already cached and the lockfile is current, steps 2 to 4 need no network at all. Cargo goes straight to compiling, and only recompiles what changed.
A first walkthrough
Here is the smallest useful example. Create a project, add a dependency, and use it.
cargo new registry_tour
cd registry_tour
cargo add serde_jsoncargo add fetched index data for serde_json, then edited Cargo.toml. Open it and you will see a [dependencies] table with a line like serde_json = "1.0.x". The exact version depends on what was newest when you ran the command. The next chapter explains this table.
Now replace src/main.rs with:
fn main() {
let value = serde_json::json!({ "name": "demo", "ok": true });
println!("{value}");
}Run it:
cargo runOn the first run, Cargo prints lines such as Locking, Downloaded, and Compiling for serde_json and the packages it depends on, then Running. The program prints:
{"name":"demo","ok":true}Run cargo run a second time and the download and compile lines are gone. The dependencies are cached and already built, so Cargo only runs your program.
Notice that you wrote serde_json::json! without any use or extern crate line. Cargo passes each dependency to rustc by name, so its crate name is available as a path in your code. If a package name contains a hyphen, such as serde-json-core, the crate name in code uses an underscore: serde_json_core.
Where everything ends up
Knowing the locations helps when something goes wrong or when you need to free disk space.
| Location | Contents |
|---|---|
| `Cargo.toml` (project root) | Your declared dependencies and their version requirements. You edit it. |
| `Cargo.lock` (project root) | The exact versions Cargo chose. Cargo edits it. |
| `target/` (project root) | Build output: compiled dependencies, your binary, incremental data. Safe to delete. |
| `~/.cargo/registry/` | Shared download cache and unpacked source for all your projects. |
The registry directory lives under CARGO_HOME, which defaults to ~/.cargo (on Windows, %USERPROFILE%\.cargo). It is shared across every project on your machine, so two projects that use the same version of a crate download it once. The target/ directory is per project, so each project compiles its own copy of its dependencies. This is why a fresh project with many dependencies takes a while on its first build, and why target/ can grow to gigabytes.
You can read the downloaded source of any dependency in ~/.cargo/registry/src/. This is useful when documentation is thin and you want to see what a function does.
What you are trusting
Adding a dependency is a decision, not just a convenience. A few facts shape how you should think about it.
- Dependencies are code that runs on your machine. A dependency compiles with your project and runs inside your program. Build scripts and procedural macros even run during compilation. crates.io does not review published code for safety.
- Dependencies bring their own dependencies. One line in your manifest can add dozens of packages. Each is more code to compile, more to update, and more to trust.
cargo tree, covered in a later chapter, shows the full set. - Published versions are permanent. That gives you reproducible builds, but it also means a vulnerable version stays available. Keeping up with updates is your job.
- Compile time grows with dependencies. Cargo builds dependencies from source, so a heavy dependency costs time on clean builds and in CI.
None of this argues against using crates. It argues for knowing what each line of your Cargo.toml pulls in.
Common problems at this stage
These errors appear for new users often enough to recognize now.
no matching package named 'x' found. The package name is misspelled, or it doesn't exist on crates.io. Check the exact name on crates.io. Names likeserde_jsonandserde-jsonare different packages.failed to get 'x' as a dependencyor network errors. Cargo could not reach the index or download server. Check your connection, proxy settings, and any corporate mirror configuration. Adding--offlinemakes Cargo use only the local cache, which works only for packages you have already downloaded.unresolved importoruse of undeclared crate or module. The dependency isn't inCargo.toml, or you used the package name where the crate name differs (hyphen versus underscore).- Surprise rebuilds. Changing the compiler version, build profile, or enabled features makes Cargo recompile dependencies. This is expected.
Summary of roles
crates.io stores published, immutable releases and an index of their metadata. Cargo reads your manifest, resolves a consistent set of versions using that index, records the result in Cargo.lock, downloads and caches sources, and compiles everything in dependency order. You declare what you need, and Cargo does the bookkeeping. The rest of this tutorial covers how to declare it well.
Exercise
You run cargo build in a project with dependencies, then run it again without changing anything, and the second run prints no download or compile lines. Which two of Cargo's earlier outputs make that possible, and where does each live?
Show answer
The downloaded and unpacked crate sources are cached in the shared registry directory under CARGO_HOME (by default ~/.cargo/registry). The compiled dependency output is cached in the project's target/ directory. Because the lockfile (Cargo.lock) already pins the versions, Cargo needs no new resolution or download, and because the target/ artifacts are up to date, it needs no recompilation.
Exercise
A teammate says "I added serde-json to Cargo.toml but use serde_json::Value; fails, and cargo add said there was no matching package." What are two possible causes, and how would you check each?
Show answer
First, the package name may be wrong. serde-json and serde_json are different names on crates.io, so search crates.io for the exact name and use that in the manifest. Second, if the dependency was added correctly, the crate name in code may differ from the package name. Hyphens in a package name become underscores in code, so check that the code path uses the underscore form of the package name. Run cargo tree to confirm which package Cargo actually resolved.