Sub topic 1
What crates.io and Cargo do for your project
Prerequisites
You should have Rust and Cargo installed. You should know basic Rust syntax and modules, and be comfortable running commands in a terminal. This chapter assumes you can create a project with cargo new.
What crates.io and Cargo do for your project
A crate is a Rust package. crates.io is the public registry where developers publish crates. A crate can provide reusable code, such as JSON serialization, HTTP clients, or command-line parsing.
Cargo is Rust’s build tool and dependency manager. It reads your project’s Cargo.toml file, downloads required crates from their sources, compiles them, and passes them to the Rust compiler. Cargo also records the exact resolved versions in Cargo.lock.
Declaring dependencies in Cargo.toml
Cargo.toml is the project manifest. Its [dependencies] table lists crates needed by the application or library.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Here, serde provides serialization traits, and its derive feature enables generated implementations. serde_json provides JSON support. The version strings are version requirements, not always exact versions. Cargo resolves versions that satisfy those requirements and records the result in Cargo.lock.
A manifest change describes what your project allows. The lock file describes what Cargo selected for this checkout.
Adding and removing dependencies with cargo add and cargo remove
The cargo add subcommand edits Cargo.toml for you. These commands create a project, enter it, and add two crates:
cargo new json_demo
cd json_demo
cargo add serde --features derive
cargo add serde_jsonYou can then use the crates in Rust code with use statements and compile the project with cargo build. Cargo downloads the crates only when they are needed.
Remove a direct dependency with:
cargo remove serde_jsonCargo updates the manifest. It may also remove transitive packages that no longer serve another dependency.
Exercise
Which file declares that a project depends on serde, and which file records the exact versions Cargo resolved?
Show answer
Cargo.toml declares the dependency requirement. Cargo.lock records the resolved versions.