Cargo.toml
- Rust course
- Intermediate
- Lesson 78/115
- 4 min
Add dependencies with Cargo.toml.
Cargo.toml
Cargo.toml defines the package's identity and dependencies. It's in TOML format: [section] headers and key = value lines:
[package]
name = "fatura"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
rand = "0.8"
[dev-dependencies]
pretty_assertions = "1"edition decides which edition's rules the language is compiled with (2015, 2018, 2021, 2024); crates on different editions work together.
Cargo.lock
Cargo.lock records the exact version of every resolved dependency, so everyone gets the same build. In binary projects it's committed to version control. cargo update moves to the newest versions within the allowed range, and cargo add serde adds a dependency to Cargo.toml.
$ cargo add rand
$ cargo tree # dependency tree
$ cargo update -p randPractice Read a TOML line
Split the text let girdi = "edition = \"2021\""; with split_once('='), trim both sides and remove the quotes from the value with trim_matches('"'). Print it as edition: 2021.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let girdi = "edition = \"2021\"";
let (anahtar, deger) = girdi.split_once('=').unwrap();
let anahtar = anahtar.trim();
let deger = deger.trim().trim_matches('"');
println!("{}: {}", anahtar, deger);
}Expected output
edition: 2021
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When are dependencies under <code>[dev-dependencies]</code> compiled?
- In every build
- Only in a release build
- Never
- Only for tests, examples and benchmarks Correct answer
Explanation: Users of the library don't download dev-dependencies; ideal for test tools.
2 Dependency section
[____]
rand = "0.8"
[dependencies]
rand = "0.8"
Explanation: Runtime dependencies go under [dependencies].
3 Key and meaning
| Term | Meaning |
|---|---|
name |
Package name |
version |
Package version |
edition |
Language edition rules |
[dev-dependencies] |
Test dependencies |