A crate is the file or files that go together as Rust code. Modules organize code inside a crate and help control what others can use. An external crate is a different crate, usually written by someone else; crates published on crates.io can be used by other projects. section 14.1 section 16.5
External crates are a normal way to add functionality in Rust, whose standard library is relatively small. For example, random-number functions are not in the standard library, so you can use the rand crate. section 16.5 section 16.5.1
To use a published crate in a local Cargo project:
- Find the crate on crates.io and add its name and version under [dependencies] in Cargo.toml. Alternatively, run cargo add rand for rand. section 16.5.1
- Run cargo run. Cargo brings in the crate’s code; its paths start with the crate name, such as rand, rather than std. section 16.5.1
[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 places rand = "0.8.5" under [dependencies]. section 16.5.1
Roll one six-sided die
With rand added, use rand::{thread_rng, Rng}; then let mut generator = thread_rng(); and let roll = generator.gen_range(1..=6);. The rand example also uses these calls to roll dice for character statistics. section 16.5.3

