Cargo is Rust’s package manager and build tool. It gives projects a common structure and uses rustc to compile them, while taking care of the work needed to bring in external crates. A crate is a Rust project or a piece of code a project can use. section 18.1 section 18.1.1
A small Cargo project starts with a few commands:
- Run `cargo new my_project` to create a project with `Cargo.toml` and `src/main.rs`. Add `--lib` if you want a library with `src/lib.rs` instead. section 18.1.1
- Add an external crate under `[dependencies]` in `Cargo.toml`, or use a command such as `cargo add rand`. section 16.5.1
- Run `cargo run` to build and run the program. Use `cargo build` to compile after adding a crate, so later builds can benefit from incremental compilation. section 18.1.1 section 18.1.2
[package] name = "rust_book" version = "0.1.0" authors = ["David MacLeod"] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rand = "0.8.5"
This `Cargo.toml` example puts `rand = "0.8.5"` under `[dependencies]`. Cargo uses that entry when building the project. section 16.5.1
Why use Cargo?
A standalone file can be compiled with `rustc test.rs`, but trying to use `rand` that way produces a missing-crate error. In a Cargo project, add `rand` as a dependency and run `cargo run`: Cargo compiles the needed crates before starting the program. On a later run, unchanged dependencies need not be recompiled. section 18.1.1 section 18.1.2




