How to clean Rust build artifacts with Cargo

Cargo build output can grow quickly during local Rust development because debug builds, test binaries, generated docs, and incremental compiler state accumulate under target/. Removing that generated output frees disk space and forces the next build to start from a fresh artifact directory.

Plain cargo clean works from a package or workspace root and removes generated artifacts, not source files, Cargo.toml, or Cargo.lock. Cargo chooses the target directory from project config, CARGO_TARGET_DIR, or --target-dir, so confirm the active artifact directory before cleaning a project that uses a shared build cache.

Use cargo clean --dry-run when the cleanup should be previewed before deletion. A follow-up cargo build recreates target/ and confirms the source tree still compiles after the cleanup.

Steps to clean Rust build artifacts with Cargo:

  1. Open a terminal in the Rust package or workspace root to clean.

    The directory should contain Cargo.toml. For a workspace, start at the workspace root when the shared target/ directory should be removed.

  2. Check that the default target directory contains generated artifacts.
    $ ls target
    CACHEDIR.TAG
    debug

    If target/ does not exist, the default target directory already has no generated artifacts to remove.

  3. Preview the cleanup without deleting files.
    $ cargo clean --dry-run
         Summary 23 files, 8.4MiB total
    warning: no files deleted due to --dry-run

    Copy release binaries, generated documentation, or timing reports out of target/ before continuing if they are deliverables that must be archived.

  4. Remove Cargo's generated artifacts.
    $ cargo clean
         Removed 23 files, 8.4MiB total

    Use cargo clean --release when only release-profile artifacts should be removed, or cargo clean --target-dir path/to/target when the project uses a custom target directory.

  5. Confirm that the default target directory is gone.
    $ ls target
    ls: cannot access 'target': No such file or directory
  6. Rebuild the package to recreate generated artifacts.
    $ cargo build
       Compiling hello-rust v0.1.0 (/work/hello-rust)
        Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s

    Run cargo test instead when the cleanup is part of a dependency change, release check, or troubleshooting pass that needs test coverage.
    Related: How to run Rust tests with Cargo
    Related: How to check Rust code with Cargo