Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 132 ยท Getting Started

Cargo, Projects and Crates

Learn Cargo, Rust's build tool - cargo new, build, run, check and test, the Cargo.toml file, src layout, dependencies and semver, features, workspaces, Cargo.lock, rustfmt and clippy.

Single-file programs are perfect for learning, but real Rust programs are projects: several files, dependencies on other people's code, tests, documentation and build settings. In Rust all of this is handled by one tool, Cargo. It creates projects, builds and runs them, downloads and compiles dependencies, runs your tests, formats your code and publishes libraries. Almost every Rust developer types cargo far more often than rustc.

This lesson explains the Cargo commands you use daily, the anatomy of Cargo.toml, how a project is laid out, how dependencies and versions work, and what features, workspaces and Cargo.lock are for. Because Cargo is a command-line tool that needs a real file system and network access, most examples here are read-only blocks that show a terminal session. The runnable examples use Rust's module system to recreate the shape of a project inside one file. After this lesson you will know how to read any Rust project you find.

Our online editor compiles one main.rs with rustc and the standard library only. It does not run Cargo and cannot download crates. Everything on this page marked read-only is for your own computer, where you install Rust with rustup (see how Rust works).

The everyday commands

Here is a complete first session in a terminal. Lines starting with $ are what you type.

Terminal
# read-only: a terminal session on your own computer
$ cargo new hello_cargo
    Creating binary (application) `hello_cargo` package
$ cd hello_cargo
$ cargo run
   Compiling hello_cargo v0.1.0 (/home/you/hello_cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.4s
     Running `target/debug/hello_cargo`
Hello, world!

cargo new makes a folder with a Cargo.toml, a src/main.rs containing a hello-world program, a .gitignore and (by default) a git repository. cargo run compiled it and ran it. The commands you will use constantly are:

Command What it does
cargo new name Creates a new binary project (--lib for a library)
cargo check Type- and borrow-checks without producing a binary; the fastest feedback
cargo build Compiles a debug build into target/debug/
cargo build --release Compiles an optimized build into target/release/
cargo run Builds if needed and runs the program; arguments go after --
cargo test Builds and runs all tests
cargo doc --open Generates HTML documentation for your code and dependencies
cargo fmt Formats all code with rustfmt
cargo clippy Runs the Clippy linter
cargo add name Adds a dependency to Cargo.toml
cargo update Moves Cargo.lock to newer compatible versions
cargo clean Deletes the target/ folder

A good rhythm while writing code is cargo check as you go, cargo test before you commit, and cargo run --release only when you care about speed. The target/ folder can grow to gigabytes; it is a cache and is never committed to git.

Anatomy of Cargo.toml

Cargo.toml (written in the TOML format) is the manifest of a package. This is the file cargo new generated:

TOML
# read-only: Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"

[dependencies]
  • [package] describes the package. name is the crate name (it becomes the binary name), version follows semantic versioning, and edition selects the language edition.
  • [dependencies] lists the crates your code uses. It is empty for now.
  • Optional keys fill in publishing details: description, license, repository, authors, rust-version (the oldest compiler you support) and more.
  • Other sections include [dev-dependencies] (only for tests and examples), [build-dependencies] (for build scripts), [features], [profile.release] for optimizer settings and [workspace].

Here is a more complete example for a small tool, with tuning for the release profile:

TOML
# read-only: a fuller Cargo.toml
[package]
name = "word-stats"
version = "0.3.2"
edition = "2024"
description = "Counts words in text files"
license = "MIT OR Apache-2.0"
rust-version = "1.85"

[dependencies]
clap = { version = "4", features = ["derive"] }
serde = { version = "1", features = ["derive"] }

[dev-dependencies]
pretty_assertions = "1"

[profile.release]
opt-level = 3
lto = true        # link-time optimization: slower build, faster program
codegen-units = 1
panic = "abort"   # smaller binary; panics end the process instead of unwinding

The layout of a project

Cargo relies on conventions, so you rarely have to configure anything:

TEXT
hello_cargo/
|-- Cargo.toml
|-- Cargo.lock          (created on first build)
|-- src/
|   |-- main.rs         (crate root of the binary)
|   |-- lib.rs          (crate root of the library, if any)
|   |-- parser.rs       (a module: `mod parser;`)
|   `-- bin/
|       `-- extra.rs    (another binary)
|-- tests/
|   `-- integration.rs  (integration tests)
|-- examples/
|   `-- demo.rs         (run with cargo run --example demo)
|-- benches/            (benchmarks)
`-- target/             (build output, not committed)

A package can have one library crate and any number of binary crates. src/main.rs is the root of the default binary, src/lib.rs the root of the library, and each file in src/bin/ is another binary. A common professional layout puts the real logic in lib.rs (easy to test) and keeps main.rs tiny.

Files in src/ become modules. If main.rs contains mod parser;, the compiler looks for src/parser.rs (or src/parser/mod.rs) and treats its contents as module parser. You can write the same thing inline with braces, and since our editor has only one file, the lessons do exactly that. This is a project's structure squeezed into one runnable file:

Rust A project layout in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Items inside a module are private unless marked pub, and super means "the parent module". Modules covers privacy, paths and use in depth.

Dependencies and semantic versioning

You add a dependency by naming the crate and a version in [dependencies], or by running cargo add serde. On the next build Cargo downloads the crate and everything it depends on from crates.io, compiles them, and links them in. The code is then available under the crate's name:

Rust
// read-only: needs the `rand` crate, not available in our editor
use rand::Rng;

fn main() {
    let roll = rand::rng().random_range(1..=6);
    println!("You rolled a {roll}");
}

Versions follow semantic versioning (semver): MAJOR.MINOR.PATCH. Patch releases fix bugs, minor releases add features compatibly, and major releases may break your code. The string "1.4" in Cargo.toml is shorthand for ^1.4, which means "any version from 1.4.0 up to, but not including, 2.0.0". Other forms exist:

Requirement Allowed versions
"1.4.2" or "^1.4.2" 1.4.2 up to below 2.0.0
"0.3" 0.3.0 up to below 0.4.0 (below 1.0, the minor version acts like a major)
"~1.4.2" 1.4.2 up to below 1.5.0
"=1.4.2" exactly 1.4.2
">=1.2, <1.5" a custom range
"*" anything (avoid; crates.io refuses it)

Because compatible versions are allowed, the same Cargo.toml could resolve to different versions next month. This is where Cargo.lock comes in. The first build records the exact version of every crate (including indirect ones) in Cargo.lock, and later builds reuse those exact versions until you run cargo update. For applications you commit Cargo.lock, so every developer and your server build the identical program. Libraries historically did not commit it, because their users resolve versions themselves.

To feel how semver ranges work, here is a tiny stand-in written with the standard library. It parses "MAJOR.MINOR.PATCH" and applies the caret rule:

Rust A tiny semver check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Deriving PartialOrd on a struct compares the fields in order, so major beats minor beats patch, exactly what version ordering needs. The real semver crate also handles pre-release tags like 1.0.0-beta.2 and the other operators in the table.

Features

Crates can offer features: optional parts that you switch on from Cargo.toml. A feature usually enables extra code (and sometimes extra dependencies). In the word-stats example, serde = { version = "1", features = ["derive"] } turns on the derive macros of serde. Library authors declare features, and application authors choose them:

TOML
# read-only: a library declaring features
[features]
default = ["json"]        # on unless the user opts out
json = ["dep:serde_json"] # enables an optional dependency
verbose = []              # a plain flag with no dependency

In code you test for a feature with the cfg attribute or macro. A compiled-out feature leaves no trace in the binary. The example below uses the built-in debug_assertions and platform settings, which work without Cargo (our editor compiles with rustc directly, so no Cargo features exist there, but these built-in switches do). It prints debug, linux and 64 bits on our server:

Rust Conditional compilation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Only one of the two build_kind functions exists after compilation, which is how libraries ship debug-only code or platform-specific implementations at no cost. More on this in attributes and cfg and Cargo features and release.

Workspaces

When a project grows into several related crates, you can group them in a workspace: a folder whose top Cargo.toml lists the members. All members share one Cargo.lock and one target/ folder, so common dependencies are compiled once.

TOML
# read-only: the root Cargo.toml of a workspace
[workspace]
members = ["app", "core", "cli"]
resolver = "3"

[workspace.dependencies]
serde = "1"       # members write `serde = { workspace = true }`

Workspaces keep compile times down and let you split code into clear layers (for instance a pure core library, a cli front end, and a server), and cargo test --workspace tests them all. Large open-source projects such as compilers and web frameworks are workspaces.

Formatting, linting, testing and docs

Cargo has companions that you install with rustup and call as subcommands:

  • cargo fmt runs rustfmt, which rewrites your code into the standard style. Teams run it automatically so nobody argues about braces.
  • cargo clippy runs Clippy, a linter with hundreds of checks for correctness, speed and style. It will tell you, for instance, that a manual loop could be an iterator chain. Treat its suggestions as a free code review.
  • cargo test runs unit tests (in your source files), integration tests (in tests/) and documentation tests (code in /// comments). See testing.
  • cargo doc builds browsable documentation from your doc comments (comments and docs).
Terminal
# read-only: a typical pre-commit routine
cargo fmt
cargo clippy -- -D warnings   # turn warnings into errors
cargo test

Checking your project from the code

A single file can still use one Cargo idea: tests live next to code. This program contains a test module; it is compiled only by cargo test (or rustc --test), so it does nothing when you run the program normally:

Rust A test module that stays dormant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The #[cfg(test)] attribute means the module vanishes from normal builds. On your machine, cargo test would build with the test configuration, run adds_numbers, and report test result: ok. 1 passed. The testing lesson shows how to run tests inside the editor with a small hand-written harness.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command gives the fastest feedback on compile errors without producing an executable?

    cargo check runs the front half of the compiler (parsing, type checking, borrow checking) and skips code generation, so it finishes much faster than a build.
  2. 2. What does the requirement serde = "1.4" in Cargo.toml allow?

    A bare version is a caret requirement: ^1.4 allows 1.4.0 up to but excluding 2.0.0. For ~1.4 you would get only 1.4.x.
  3. 3. Why do you normally commit Cargo.lock for an application?

    Cargo.lock pins every direct and indirect dependency to the exact version that was resolved, giving reproducible builds.
  4. 4. Where is the entry point of the default binary crate in a new Cargo package?

    src/main.rs is the crate root of the default binary, and it contains fn main. src/lib.rs is the root of the library crate.
  5. 5. What is a workspace?

    A workspace lists member packages in a root Cargo.toml. They share the lock file and build output, which saves compile time and keeps versions consistent.

Summary

  • Cargo creates projects (cargo new), checks (cargo check), builds (cargo build [--release]), runs, tests, documents, formats and lints them.
  • Cargo.toml holds the package metadata, dependencies, features and profiles; src/main.rs and src/lib.rs are the crate roots.
  • Dependencies come from crates.io and use semver requirements; a bare "1.4" means ^1.4. Cargo.lock pins the exact versions and is committed for applications.
  • Features switch optional parts of a crate on, and cfg attributes compile code in or out.
  • A workspace groups several packages that share a lock file and a build directory.
  • Our editor runs a single file with only the standard library, so the Cargo parts of this tutorial are read-only blocks next to runnable stand-ins.

Next: Comments and Documentation