Crate (Rust)

A crate is the unit of compilation and distribution in Rust — either a binary crate (an executable with a main function) or a library crate (reusable code other crates depend on).

Rust

Every Rust project compiles down to one or more crates. A binary crate produces a runnable program; a library crate produces code meant to be used by other crates and has no main. The crate root is the source file the compiler starts from — src/main.rs for binaries, src/lib.rs for libraries.

Crates are also the packages you depend on. When you add serde or rand under [dependencies] in Cargo.toml, you are pulling in external library crates downloaded from crates.io, Rust's package registry.

Within a crate, code is organized into modules (mod). So the hierarchy is: a package (managed by Cargo) contains one or more crates, and each crate contains a tree of modules.

Syntax

// import an item from an external crate
use rand::Rng;

Examples

Rust — A library crate exposes pub items for others to use.

// src/lib.rs of a library crate
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

Learn it in a lesson

See also

Back to the Dictionary