Files
100-exercises-to-learn-rust/book/src/05_ticket_v2/11_dependencies.md
LukeMathWalker 4401743807 Formatter
2024-05-24 18:16:20 +02:00

2.1 KiB
Raw Blame History

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, Rusts 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 youre 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 youre working on multiple local packages.

[dependencies]
my-library = { path = "../my-library" }

The path is relative to the Cargo.toml file of the package thats 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 youre running cargo test.
They go in the [dev-dependencies] section of your Cargo.toml file:

[dev-dependencies]
static_assertions = "1.1.0"

Weve been using a few of these throughout the book to shorten our tests.