Cargo

Package ManagerRustBuild SystemCrates.ioWorkspaceEdition 2024Integrated Toolchain

Package Manager

Cargo

Overview

Cargo is the official package manager and build system for the Rust programming language, providing integrated dependency management, project building, test execution, and package publishing. It offers project configuration through Cargo.toml files, integration with the crates.io ecosystem, and workspace functionality for large-scale project management. Cargo 2.0, released in 2024, achieves significant build speed improvements, smart dependency handling, and simplified development workflows through new command sets. With Rust Edition 2024 support, it provides a fully integrated development experience with the latest language features.

Details

Cargo was developed in 2014 as part of the Rust project, achieving tight integration between the language and package manager. Project metadata and dependencies are managed through Cargo.toml files, while Cargo.lock files lock exact versions to ensure reproducible builds. Crates.io serves as Rust's central package repository, handling distribution of open-source libraries. The workspace feature enables efficient management of multiple related crates within a single project. Advanced features like build scripts, custom targets, and conditional compilation support a wide range of applications from systems programming to web applications. Edition 2024 support provides complete compatibility with the latest Rust language features.

Pros and Cons

Pros

  • Integrated toolchain: Unified tool for package management, building, testing, and publishing
  • Zero configuration: Standard settings ready for immediate use in new projects
  • Fast builds: Acceleration through incremental compilation and parallel builds
  • Workspace functionality: Efficient management of multiple crates
  • Semantic versioning: Automatic compatibility checking
  • Rich ecosystem: High-quality library collection in Crates.io
  • Cross-compilation: Multi-platform build support

Cons

  • Rust-specific: Cannot be used with languages other than Rust
  • Learning curve: Initial complexity due to feature richness
  • Compilation time: Long compilation times for large projects
  • Dependency size: Bloated build artifacts due to transitive dependencies
  • Compatibility constraints: Dependencies between Rust editions and Cargo versions
  • Network dependency: Requires access to crates.io

Reference Links

Code Examples

Basic Project Management

# Create new project
cargo new my_project
cargo new my_library --lib

# Initialize in existing directory
cargo init
cargo init --lib

# Build dependencies
cargo build
cargo build --release

# Run tests
cargo test
cargo test --lib
cargo test integration_tests

# Run project
cargo run
cargo run --bin my_binary
cargo run --example example_name

# Check (type checking and compilation errors)
cargo check
cargo check --all-targets

Cargo.toml Configuration (Edition 2024)

[package]
name = "my_project"
version = "0.1.0"
edition = "2024"
authors = ["Your Name <[email protected]>"]
description = "A sample Rust project"
license = "MIT OR Apache-2.0"
repository = "https://github.com/username/my_project"
documentation = "https://docs.rs/my_project"
homepage = "https://my_project.example.com"
readme = "README.md"
keywords = ["cli", "example", "rust"]
categories = ["command-line-utilities"]
rust-version = "1.75"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
clap = { version = "4.0", features = ["derive"] }
anyhow = "1.0"
tracing = "0.1"
uuid = { version = "1.0", features = ["v4", "serde"] }

[dev-dependencies]
mockall = "0.12"
criterion = { version = "0.5", features = ["html_reports"] }
tempfile = "3.0"

[build-dependencies]
cc = "1.0"

[features]
default = ["cli"]
cli = ["clap"]
web = ["axum", "tower"]
experimental = []

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"

[profile.dev]
opt-level = 0
debug = true

Workspace Configuration

# Root Cargo.toml (workspace definition)
[workspace]
members = [
    "core",
    "cli",
    "web-api",
    "shared-types"
]
default-members = ["cli"]
resolver = "2"

[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", default-features = false }
anyhow = "1.0"
uuid = { version = "1.0", features = ["v4"] }

[workspace.package]
version = "0.1.0"
edition = "2024"
authors = ["Your Name <[email protected]>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/username/my_workspace"

# Workspace-wide settings
[profile.release]
lto = true
codegen-units = 1
# Member crate: core/Cargo.toml
[package]
name = "my-core"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true

[dependencies]
serde.workspace = true
uuid.workspace = true
anyhow.workspace = true

[lib]
name = "my_core"
crate-type = ["lib"]

Advanced Dependency Specification

[dependencies]
# Version specification types
time = "0.3.0"              # >=0.3.0, <0.4.0
regex = "~1.5"              # 1.5.x series
log = ">=0.4.0, <0.5.0"     # Range specification
chrono = "^0.4"             # Caret (equivalent to ^0.4.0)

# Git dependencies
my-git-dep = { git = "https://github.com/user/repo.git", branch = "main" }
another-dep = { git = "https://github.com/user/repo.git", tag = "v1.0" }
specific-commit = { git = "https://github.com/user/repo.git", rev = "abc123" }

# Path dependencies
local-lib = { path = "../local-lib" }
workspace-member = { path = "crates/shared" }

# Conditional dependencies
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winuser", "shellapi"] }

[target.'cfg(unix)'.dependencies]
libc = "0.2"

# Optional dependencies
[dependencies]
serde_json = { version = "1.0", optional = true }

[features]
json = ["serde_json"]

Building and Testing

# Various build options
cargo build --all-targets          # Build all targets
cargo build --workspace           # Entire workspace
cargo build --package my-core     # Specific package
cargo build --features json       # Enable specific features
cargo build --no-default-features # Disable default features

# Test execution
cargo test --workspace           # Entire workspace
cargo test --package my-core     # Specific package
cargo test --lib                # Library tests only
cargo test --bins               # Binary tests only
cargo test --examples           # Example tests
cargo test unit_tests           # Specific tests

# Benchmarking
cargo bench
cargo bench --package my-core

# Documentation generation
cargo doc --open              # Generate docs and open in browser
cargo doc --no-deps           # Exclude dependency docs
cargo doc --workspace         # Entire workspace

Package Publishing

# Packaging
cargo package                  # Create .crate file
cargo package --list          # List included files
cargo package --allow-dirty    # Allow uncommitted changes

# Pre-publication checks
cargo publish --dry-run       # Dry run publication

# Publishing
cargo publish                 # Publish to crates.io
cargo publish --registry my-registry  # Publish to custom registry

# Crate information search
cargo search serde           # Search on crates.io
cargo search --limit 20 web  # Limit search results

Advanced Features and Configuration

# Custom build script
[package]
build = "build.rs"

# Target-specific configuration
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"

[target.'cfg(target_os = "linux")']
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

# Patches (dependency overrides)
[patch.crates-io]
my-crate = { git = "https://github.com/user/my-crate", branch = "fix" }
serde = { path = "../serde" }

# Custom registries
[registries]
my-registry = { index = "https://my-registry.com/git/index" }

# Configuration
[source.crates-io]
replace-with = "my-mirror"

[source.my-mirror]
registry = "https://my-mirror.com/git/index"

Workspace Development Workflow

# Workspace-wide operations
cargo build --workspace
cargo test --workspace
cargo check --workspace

# Specific crate operations
cargo build -p my-core
cargo test -p my-cli
cargo run -p my-web-api

# Dependency management
cargo tree                    # Display dependency tree
cargo tree -p my-core         # Dependencies for specific package
cargo tree --duplicates       # Show duplicate dependencies

# Metadata retrieval
cargo metadata               # Output project info as JSON
cargo metadata --format-version 1

# Cleanup
cargo clean                  # Remove build artifacts
cargo clean -p my-core       # Specific package only

CI/CD and Performance Optimization

# CI environment acceleration
export CARGO_HOME=/usr/local/cargo
export RUSTC_WRAPPER=sccache      # Compilation cache

# Cache optimization
cargo fetch                       # Pre-fetch dependencies
cargo build --frozen             # Prohibit Cargo.lock changes
cargo build --offline            # Offline build

# Performance analysis
cargo build --timings            # Measure compilation time
cargo bloat                      # Binary size analysis (requires cargo-bloat)
cargo audit                      # Security audit (requires cargo-audit)

# Parallel testing
cargo test -- --test-threads=4  # Specify parallel test count
cargo test -- --nocapture       # Show test output