TechSetupGuides
Beginnercargorustpackage-managerbuild-systemdependenciescrates-ioworkspaceclicompilationrust-toolchain

Cargo - Rust Package Manager

Install and use Cargo, the Rust package manager and build system that manages your Rust project dependencies, compiles your code, and handles publishing packages to crates.io — covering installation, configuration, project management, and common use cases.

  1. Step 1

    Overview

    Cargo is the package manager and build system for the Rust programming language. It handles dependency management, compilation, testing, documentation generation, and publishing of Rust packages (crates) to crates.io, the official Rust package registry.

    Key Features:

    • Dependency Management: Automatically download and manage project dependencies from crates.io
    • Build System: Compile Rust code with intelligent caching and incremental compilation
    • Workspace Support: Manage multiple related crates in a single project
    • Testing Framework: Built-in test runner with parallel execution
    • Documentation: Generate API documentation with cross-references
    • Package Publishing: Publish crates to crates.io with versioning
    • Cross-Compilation: Build for different target platforms
    • Audit & Security: Integrated security auditing with cargo-audit

    Why Cargo:

    • Simple: Declarative dependency management in Cargo.toml
    • Fast: Parallel builds, incremental compilation, caching
    • Reliable: Deterministic builds, reproducible results
    • Secure: Cryptographic verification of downloaded crates
    • Standard: Ships with Rust, no additional installation needed
    Official Docs: https://doc.rust-lang.org/cargo/
    GitHub: https://github.com/rust-lang/cargo (15K+ stars)
    Crates.io Registry: https://crates.io
    Cargo Book: https://doc.rust-lang.org/cargo/book/
  2. Step 2

    Installation

    Cargo comes bundled with Rust via rustup (the Rust toolchain installer). If you have Rust installed, you already have Cargo.

    Installation methods:

    1. rustup (recommended) - installs Rust + Cargo together
    2. Package managers - OS-specific packages
    3. Standalone - manual binary installation
    # Option 1: rustup (Recommended) - Installs Rust + Cargo
    # This is the official and recommended way
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    # Or with specific version
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain stable
    
    # Option 2: Package Managers
    # Ubuntu/Debian
    sudo apt update && sudo apt install cargo
    
    # Fedora
    sudo dnf install cargo
    
    # Arch Linux
    sudo pacman -S cargo
    
    # macOS (Homebrew)
    brew install rustup
    # Then run:
    rustup init
    
    # Option 3: Manual Download
    # Download from: https://github.com/rust-lang/cargo/releases
    # Extract to $HOME/.cargo/bin or /usr/local/bin
    
    # Verify installation
    cargo --version
    # Should print: cargo 1.85.0 (or similar)
    
    # Verify Rust compiler
    rustc --version
    
    # Add to PATH if not automatic
    # Add to ~/.bashrc or ~/.zshrc:
    export PATH="$HOME/.cargo/bin:$PATH"
  3. Step 3

    Toolchain Management

    Manage Rust toolchains with rustup. Switch between stable, beta, and nightly, and add cross-compilation targets.

    # Check which toolchain is active
    rustup show
    
    # Install specific toolchain
    rustup install stable
    rustup install 1.80.0
    rustup install nightly
    
    # Set default toolchain
    rustup default stable
    
    # Add target for cross-compilation
    rustup target add wasm32-unknown-unknown
    rustup target add aarch64-unknown-linux-gnu
    
    # Update Rust and Cargo
    rustup update
    
    # Uninstall specific version
    rustup uninstall nightly
  4. Step 4

    Creating Projects

    Use cargo new to scaffold a new binary or library project. Cargo creates the directory structure and a starter Cargo.toml automatically.

    # Create a new project
    cargo new my_rust_project
    cd my_rust_project
    
    # Directory structure:
    # my_rust_project/
    # ├── Cargo.toml      # Manifest file
    # ├── src/
    # │   └── main.rs     # Source code
    # └── target/         # Build artifacts (gitignored)
  5. Step 5

    Cargo.toml Configuration

    The Cargo.toml manifest defines your package metadata, dependencies, dev-dependencies, build-dependencies, and build profiles.

    [package]
    name = "my_project"          # Package name
    version = "0.1.0"            # Semantic versioning
    edition = "2021"             # Rust edition (2015, 2018, 2021, 2024)
    authors = ["Your Name <email@example.com>"]
    license = "MIT"              # License identifier
    description = "A short description"
    repository = "https://github.com/username/repo"
    homepage = "https://example.com"
    readme = "README.md"
    keywords = ["keyword1", "keyword2"]
    categories = ["development-tools", "command-line-utilities"]
    
    [dependencies]
    # Add dependencies here
    serde = { version = "1.0", features = ["derive"] }
    reqwest = "0.11"
    tokio = { version = "1", features = ["full"] }
    
    [dev-dependencies]
    # Dependencies only used for testing
    criterion = "0.5"
    mockall = "0.11"
    
    [build-dependencies]
    # Dependencies used during build.rs
    cc = "1.0"
    
    [profile.dev]
    # Development profile settings
    opt-level = 0
    debug = true
    
    [profile.release]
    # Release profile settings
    opt-level = 3
    lto = true
    
    [profile.dev.package."*"]
    # Optimize all dependencies in dev mode
    opt-level = 3
  6. Step 6

    Core Commands

    The most-used Cargo commands for building, running, testing, checking, documenting, and cleaning your project.

    # Build the project
    cargo build                    # Build in debug mode
    cargo build --release          # Build in release mode
    cargo build --verbose          # Verbose output
    cargo build --target wasm32-unknown-unknown  # Cross-compile
    
    # Run the project
    cargo run                      # Build and run in debug mode
    cargo run --release            # Build and run in release mode
    cargo run -- --args            # Pass args to your program
    
    # Check without building
    cargo check                    # Fast syntax/type checking
    cargo clippy                   # Lint checker (requires cargo clippy)
    
    # Run tests
    cargo test                     # Run all tests
    cargo test --release           # Run release tests
    cargo test test_name           # Run specific test
    cargo test -- --nocapture      # Show println! output
    
    # Generate documentation
    cargo doc                      # Generate docs
    cargo doc --open              # Generate and open in browser
    cargo doc --no-deps           # Don't document dependencies
    
    # Clean build artifacts
    cargo clean                    # Remove target/
    cargo clean --release         # Remove release builds
    
    # Update dependencies
    cargo update                  # Update Cargo.lock
    cargo update -p serde         # Update specific package
    
    # Publish to crates.io
    cargo login <api-token>       # Authenticate
    cargo publish                 # Publish current crate
    cargo publish --dry-run       # Test publishing
  7. Step 7

    Dependency Management

    Use cargo add / cargo remove (from cargo-edit) to manage dependencies, and cargo tree to inspect the dependency graph.

    cargo add serde --features derive
    cargo add reqwest@0.11
    cargo add tokio --features "full" --dev
    cargo remove serde
    cargo upgrade -p serde
    cargo upgrade --dry-run
    cargo tree                 # Show dependency tree
    cargo tree --depth 1      # Limit depth
    cargo tree -i serde       # Reverse dependency tree
  8. Step 8

    Installing Binaries

    Install binary crates from crates.io directly to ~/.cargo/bin with cargo install. Installed binaries are immediately available on your PATH.

    # Install a binary crate
    cargo install ripgrep
    cargo install bat          # Better cat
    cargo install rustfmt      # Rust formatter
    cargo install cargo-audit  # Security audit
    
    # Install to specific location
    cargo install --root $HOME/.local ripgrep
    
    # Install specific version
    cargo install ripgrep@14.1.0
    
    # Update installed crates
    cargo install ripgrep --force
    cargo install --locked ripgrep  # Use exact versions from Cargo.lock
  9. Step 9

    Workspaces

    A Cargo workspace groups multiple related crates under a single Cargo.lock and shared build output directory, making it easy to work on multi-crate projects.

    # Create workspace root
    cargo new my-workspace --name my-workspace
    cd my-workspace
    
    # Edit Cargo.toml:
    [workspace]
    members = [
        "crate1",
        "crate2",
        "path/to/crate3",
    ]
    
    # Create member crates
    cargo new crate1
    cargo new crate2 --lib
    
    # Build entire workspace
    cargo build
    
    # Run specific member
    cargo run -p crate1
    
    # Test all members
    cargo test
    
    # Benchmark all members
    cargo bench
  10. Step 10

    Publishing to crates.io

    Publish your crate to the public registry at crates.io so others can add it as a dependency. Requires a crates.io account and API token.

    # 1. Create crates.io account: https://crates.io
    # 2. Generate API token: https://crates.io/me
    # 3. Login to Cargo
    cargo login <your-api-token>
    
    # 4. Verify your crate
    cargo publish --dry-run
    
    # 5. Publish
    cargo publish
    
    # 6. View your crate
    # https://crates.io/crates/your-crate-name
    
    # 7. Update version and republish
    # Edit Cargo.toml: version = "1.0.1"
    cargo publish
  11. Step 11

    Configuration

    Cargo and build behaviour can be tuned via environment variables and a per-project (or global) .cargo/config.toml file.

    ## Configuration
    
    CARGO_HOME: Directory for Cargo registries (default: ~/.cargo)
    RUSTUP_HOME: Directory for Rust toolchains (default: ~/.rustup)
    CARGO_REGISTRIES_CRATES_IO_PROTOCOL: Protocol for crates.io (sparse, git,spi)
    
    ## Environment Variables for Builds
    
    RUSTFLAGS: Additional flags for rustc (e.g., -C opt-level=3)
    RUSTDOCFLAGS: Additional flags for rustdoc
    CARGO_INCREMENTAL: Enable incremental compilation (0 or 1)
    CARGO_BUILD_JOBS: Number of parallel jobs (default: number of CPUs)
    
    ## .cargo/config.toml
    
    [build]
    target = "x86_64-unknown-linux-gnu"
    rustflags = ["-C", "link-arg=-pthread"]
    
    [net]
    git-fetch-with-cli = true
    offline = false
    
    [registries]
    [registries.my-registry]
    index = "https://example.com/index"
    
    [alias]
    t = "test"
    b = "build"
    d = "doc --open"
  12. Step 12

    Extension Tools

    The Cargo ecosystem includes a rich set of third-party subcommands. Install them with cargo install and invoke them as cargo <subcommand>.

    # Install cargo-edit (add, remove, update dependencies)
    cargo install cargo-edit
    
    # Install cargo-audit (security vulnerabilities)
    cargo install cargo-audit
    
    # Install cargo-outdated (find outdated dependencies)
    cargo install cargo-outdated
    
    # Install cargo-expand (macro expansion)
    cargo install cargo-expand
    
    # Install cargo-udeps (find unused dependencies)
    cargo install cargo-udeps
    
    # Install cargo-binstall (faster binary installs)
    cargo install cargo-binstall
    
    # Install cargo-flamegraph (performance profiling)
    cargo install cargo-flamegraph
    
    # Install cargo-llvm-cov (code coverage)
    cargo install cargo-llvm-cov
  13. Step 13

    Security Auditing

    Use cargo-audit to check your dependency tree against the RustSec advisory database for known vulnerabilities.

    # Check for security vulnerabilities
    cargo install cargo-audit
    cargo audit
    
    # Check for outdated dependencies
    cargo install cargo-outdated
    cargo outdated
    
    # Check for unused dependencies
    cargo install cargo-udeps
    cargo udeps
    
    # Audit dependencies recursively
    cargo audit --detailed
    
    # Ignore specific vulnerabilities
    cargo audit --ignore RUSTSEC-2023-0001
  14. Step 14

    Cross-Compilation

    Cargo supports cross-compilation to any target supported by rustc. Install the target with rustup target add first.

    # Build for specific target
    cargo build --target wasm32-unknown-unknown
    
    # Cross-compile for different OS
    cargo build --target x86_64-pc-windows-gnu
    
    # Install target
    cargo install --target wasm32-unknown-unknown wasm-bindgen-cli
    
    # Check available targets
    rustup target list
    
    # Install additional target
    rustup target add wasm32-unknown-unknown
    rustup target add aarch64-unknown-linux-musl
  15. Step 15

    Build Profiles

    Cargo has two built-in profiles: dev (fast compile, debug info) and release (optimised, slow compile). Both are configurable in Cargo.toml.

    ## Debug vs Release
    
    cargo build       # Debug: slower, more info, no optimizations
    cargo build --release  # Release: faster, optimized, stripped
    
    ## Profiling
    
    [profile.release]
    debug = true        # Include debug info
    lto = true         # Link-time optimization
    codegen-units = 1  # Maximum optimization
    
    ## Benchmarking
    
    cargo bench        # Run benchmarks
    # Requires #[bench] or criterion dependency
  16. Step 16

    Best Practices

    Common errors and recommended workflows to keep your Rust project healthy and maintainable.

    ## Common Errors
    
    "cannot find macro" - missing feature or wrong import
    "expected type A, found type B" - type mismatch
    "the method `xxx` exists but is not implemented" - missing trait import
    "could not compile" - compilation error, check verbose output
    
    ## Best Practices
    
    1. Use `cargo check` before `cargo build` for faster feedback
    2. Use `--release` for production builds
    3. Use workspaces for multi-crate projects
    4. Pin dependency versions in Cargo.toml
    5. Use `cargo audit` regularly for security
    6. Document public APIs with doc comments
    7. Write tests with `#[test]` and integration tests
    8. Use `cargo fmt` to keep code formatted
    9. Use `cargo clippy` for additional linting
  17. Step 17

    Resources

    Full list of official documentation, community resources, and useful extension tools. Run cargo help to see built-in docs at any time.

    Official Docs: https://doc.rust-lang.org/cargo/
    Crate Registry (crates.io): https://crates.io
    Cargo Book: https://doc.rust-lang.org/cargo/book/
    Rust Documentation: https://doc.rust-lang.org
    Rust by Example: https://doc.rust-lang.org/rust-by-example
    Crates.io API: https://crates.io/api/v1/
    crates.io Terms: https://crates.io/terms
    
    ## Community
    
    Rust Users Forum: https://users.rust-lang.org/
    Rust Programming Language Stack Exchange: https://stackoverflow.com/questions/tagged/rust
    Rust Discord: https://discord.gg/rust-lang
    
    ## Tools
    
    cargo-edit: https://github.com/killercup/cargo-edit
    cargo-audit: https://github.com/RustSec/cargo-audit
    cargo-outdated: https://github.com/est31/cargo-outdated
    cargo-expand: https://github.com/dtolnay/cargo-expand
    cargo-flamegraph: https://github.com/flamegraph-rs/flamegraph
    cargo-llvm-cov: https://github.com/taiki-e/cargo-llvm-cov
    wasm-pack: https://rustwasm.github.io/wasm-pack/

Feature requests

Sign in to suggest features or vote on existing ones.

No feature requests yet.

Discussion

0 people marked this as worked·Sign in to mark your own.

Sign in to join the discussion.

No comments yet.