Rust Crates

A crate is a compilation unit in Rust.

Yancy Dennis
2 min readJan 3, 2023

In Rust, a crate is a compilation unit. Crates are the building blocks of Rust programs and are used to organize code and reuse it across multiple projects.

Photo by Edgar on Unsplash

There are two types of crates: binary crates and library crates.

A binary crate is an executable program. It contains a main function and can be compiled to produce an executable file.

A library crate is a collection of Rust code that can be used as a dependency for other crates. It can contain functions, types, and other code that can be called from other crates. Library crates cannot be compiled directly and must be used as a dependency for another crate.

Crates can be created using the crate keyword followed by the crate name. For example:

crate my_crate;

Crates can also be split into modules, which can be used to organize code and control visibility. Modules can be defined using the mod keyword followed by the module name. For example:

mod my_module {
// module code goes here
}

Crates can depend on other crates by using the extern crate keyword followed by the crate name. For example:

extern crate my_dependency;

Dependencies can be specified in the Cargo.toml file, which is used by the Rust build tool cargo to manage crates and their dependencies.

Here is an example of a Cargo.toml file specifying a dependency:

[dependencies]
my_dependency = "1.0.0"

This would specify that the current crate depends on the my_dependency crate with version 1.0.0.

--

--