100 exercises to learn Rust
This commit is contained in:
58
book/src/05_ticket_v2/11_dependencies.md
Normal file
58
book/src/05_ticket_v2/11_dependencies.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# 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:
|
||||
|
||||
```toml
|
||||
[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](https://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.
|
||||
|
||||
```toml
|
||||
[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](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html) 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:
|
||||
|
||||
```toml
|
||||
[dev-dependencies]
|
||||
static_assertions = "1.1.0"
|
||||
```
|
||||
|
||||
We've been using a few of these throughout the book to shorten our tests.
|
||||
|
||||
## References
|
||||
|
||||
- The exercise for this section is located in `exercises/05_ticket_v2/11_dependencies`
|
||||
Reference in New Issue
Block a user