SyntaxStudy
Sign Up
Rust Creating and Building Projects with Cargo
Rust Beginner 1 min read

Creating and Building Projects with Cargo

Cargo is Rust's build system and package manager. It handles compiling your code, downloading and compiling dependencies, running tests, generating documentation, and publishing crates to crates.io. Almost every real Rust project is managed with Cargo. The `cargo new` command scaffolds a new project: `cargo new my_app` creates a binary project, and `cargo new --lib my_lib` creates a library. The core commands are `cargo build` (compile in debug mode), `cargo build --release` (compile with optimisations), `cargo run` (build and run a binary), `cargo test` (run all tests), `cargo check` (type-check without producing a binary — much faster than build), and `cargo doc --open` (generate and open HTML documentation). These commands work from any directory within a Cargo workspace. Cargo uses a workspace model for projects that contain multiple related crates. A root `Cargo.toml` declares `[workspace]` with a `members` list, and all member crates share a single `Cargo.lock` file and a single `target` build directory. Workspaces are essential for monorepos and allow incremental compilation across multiple crates, reducing build times significantly.
Example
# Create a new binary project
# $ cargo new hello_cargo
# Created binary (application) `hello_cargo` package

# Project layout created:
# hello_cargo/
# ├── Cargo.toml
# └── src/
#     └── main.rs

# Build (debug)
# $ cargo build
# Compiling hello_cargo v0.1.0
# Finished dev [unoptimized + debuginfo] target(s) in 1.23s

# Run without a separate build step
# $ cargo run
# Hello, world!

# Type-check only (fastest way to catch errors)
# $ cargo check

# Build with optimisations
# $ cargo build --release

# Run tests
# $ cargo test

# Cargo.toml for a typical binary project:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
description = "A demo Cargo project"

[[bin]]
name = "hello_cargo"
path = "src/main.rs"

[dependencies]
# dependencies go here

[dev-dependencies]
# test-only dependencies

[profile.release]
opt-level = 3
lto = true