liveBook · Manning

Crate

As explained in Learn Rust in a Month of Lunches

An external crate is a Rust compilation unit published outside the current project for other programs to depend on.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines crates and external crates, then walks through adding a dependency and using it; does not detail Cargo’s dependency internals.
Examples
Shows a Cargo.toml entry for rand and dice rolls used to generate character statistics.
What it assumes
Assumes basic Rust code and a Cargo project for local use; defines crates and explains how to add a dependency.
What you can do after
Apply it via Cargo by adding a crate dependency and using the crate’s code in a Rust program.
How it connects
Connects crates to modules, visibility, Cargo.toml dependencies, crates.io, and the Rust standard library.

Also explained in

Compare how 2 books explain crate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.