Dependencies
A package can depend on other packages by listing them in the [dependencies]
section of its Cargo.toml
file.
The most common way to specify a dependency is by providing its name and version:
[dependencies]
thiserror = "1"
This will add thiserror
as a dependency to your package, with a minimum version of 1.0.0
.
thiserror
will be pulled from crates.io, Rust's official package registry.
When you run cargo build
, cargo
will go through a few stages:
- Dependency resolution
- Downloading the dependencies
- Compiling your project (your own code and the dependencies)
Dependency resolution is skipped if your project has a Cargo.lock
file and your manifest files are unchanged.
A lockfile is automatically generated by cargo
after a successful round of dependency resolution: it contains
the exact versions of all dependencies used in your project, and is used to ensure that the same versions are
consistently used across different builds (e.g. in CI). If you're working on a project with multiple developers,
you should commit the Cargo.lock
file to your version control system.
You can use cargo update
to update the Cargo.lock
file with the latest (compatible) versions of all your dependencies.
Path dependencies
You can also specify a dependency using a path. This is useful when you're working on multiple local packages.
[dependencies]
my-library = { path = "../my-library" }
The path is relative to the Cargo.toml
file of the package that's declaring the dependency.
Other sources
Check out the Cargo documentation for more
details on where you can get dependencies from and how to specify them in your Cargo.toml
file.
Dev dependencies
You can also specify dependencies that are only needed for developmentāi.e. they only get pulled in when you're
running cargo test
.
They go in the [dev-dependencies]
section of your Cargo.toml
file:
[dev-dependencies]
static_assertions = "1.1.0"
We've been using a few of these throughout the book to shorten our tests.
Exercise
The exercise for this section is located in 05_ticket_v2/11_dependencies