Cargo Basics
10 examples to get you started with Cargo - 7 basic and 3 intermediate.
Busca en todas las páginas de la documentación
10 examples to get you started with Cargo - 7 basic and 3 intermediate.
rustup default stable)cargo --version prints 1.97 or newercargo new scaffolds a runnable project with Cargo.toml and src/main.rs.
cargo new greeter
cd greeter
cargo runCargo.toml with [package] metadata and edition 2024src/main.rs is the binary entry pointtarget/ holds build artifacts (gitignore it)target/debug/Related: Cargo.toml Explained - manifest fields
Use --lib when building a reusable crate instead of a binary.
cargo new --lib math_utils
cd math_utilspub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds() {
assert_eq!(add(2, 2), 4);
}
}src/lib.rspub#[cfg(test)]math_utils = "0.1" to their Cargo.tomlRelated: Workspaces - multi-crate repos
cargo build compiles; cargo run compiles and executes the binary.
cargo build # debug (fast compile)
cargo build --release # optimized
cargo run -- arg1 arg2dbg! and backtraces--release uses the [profile.release] settings-- go to your program, not Cargocargo check type-checks without linking (fastest feedback loop)Related: Profiles & Build Settings - opt levels
cargo test runs unit tests, integration tests, and doctests.
cargo test
cargo test add_works -- --nocapture
cargo test --docsrc/**/*.rs under #[cfg(test)]tests/*.rs (separate crates)-- --nocapture shows println! from testsRUST_BACKTRACE=1Related: Testing Basics - full testing guide
Declare crates in [dependencies]; Cargo resolves versions and builds a lockfile.
[dependencies]
serde = { version = "1.0", features = ["derive"] }cargo add serde --features derive
cargo buildcargo add edits Cargo.toml and fetches the crateCargo.lock pins exact versions for reproducible buildsCargo.lock for binaries; libraries often omit itcargo update -p serde bumps one crate within semver boundsRelated: Dependency Management - updates and audit
A standard binary crate looks like this:
my_app/
├── Cargo.toml
├── Cargo.lock
├── src/
│ └── main.rs
└── tests/
└── integration_test.rs
src/main.rs = binary root; src/lib.rs = library root (one or both)benches/ for Criterion benchmarks; examples/ for sample binariesbuild.rs runs before compilation when native code or codegen is neededsrc/ as mod_name.rs or mod_name/mod.rsRelated: Build Scripts (build.rs) - custom build steps
Cargo subcommands help you understand what you are building.
cargo metadata --format-version 1 | jq '.packages[].name'
cargo tree -p my_app
cargo doc --opencargo tree shows the dependency graphcargo doc --open builds and opens API docs for dependenciescargo metadata is the machine-readable project graphRelated: Useful Cargo Subcommands - expand, bloat, watch
Enable optional functionality with Cargo features.
[features]
default = ["std"]
std = []
[dependencies]
log = { version = "0.4", optional = true }#[cfg(feature = "std")]
pub fn init() {
log::info!("initialized");
}cargo build --no-default-features
cargo build --features std#[cfg(feature = "...")] gates code at compile timeCargo.toml commentsRelated: Features & Optional Dependencies
Run Cargo at the workspace root to build every member crate.
cargo build --workspace
cargo test -p api
cargo run -p cli -- --help-p selects one package in a workspace--workspace builds all members sharing one Cargo.lock[workspace.dependencies] deduplicate version pinscargo test --workspace --all-featuresRelated: Workspaces - boundaries and layout
Prepare metadata, verify locally, then publish.
cargo publish --dry-run
cargo package
cargo publish[package]
name = "my_crate"
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
description = "One-line summary for crates.io"
repository = "https://github.com/org/my_crate"cargo publish --dry-run catches manifest errors earlycargo package produces the .crate tarball locallyCARGO_REGISTRY_TOKEN for non-interactive CI publishRelated: Publishing to crates.io
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026