Rust .gitignore Configuration

Proper .gitignore setup for Rust projects using Cargo. Covers the target directory, Cargo.lock decisions for libraries vs binaries, and debug artifacts.

Language

Detailed Explanation

Rust's package manager Cargo generates a substantial build cache in the target/ directory. A correct .gitignore keeps this out of version control while preserving the files that ensure reproducible builds.

Essential Rust ignore patterns:

/target/
**/*.rs.bk
*.pdb

The target/ directory:

This is where Cargo stores everything related to compilation:

  • target/debug/ — Debug build output (the default mode). Contains the compiled binary, intermediate object files, and incremental compilation caches.
  • target/release/ — Optimized release build output from cargo build --release.
  • target/doc/ — Generated documentation from cargo doc.
  • target/.fingerprint/ — Cargo's dependency tracking cache for incremental builds.
  • target/deps/ — Compiled dependency artifacts.

The target/ directory can easily grow to multiple gigabytes for projects with many dependencies. It is always fully reproducible from Cargo.toml and Cargo.lock.

The Cargo.lock decision:

This is Rust's most important .gitignore decision:

  • Binary projects (applications): Always commit Cargo.lock. It ensures every developer and CI server builds with identical dependency versions. This prevents "it compiles on my machine" issues.
  • Library crates: The Rust convention is to ignore Cargo.lock for libraries. Libraries should be tested against the latest compatible versions of their dependencies, not pinned versions. Downstream consumers use their own lockfile.

Add Cargo.lock to .gitignore only for library crates:

# Only for library crates
Cargo.lock

Other patterns:

  • **/*.rs.bk — Backup files created by rustfmt when reformatting code (older versions of the tool).
  • *.pdb — Windows debug symbol files generated during compilation on MSVC targets.

Workspace projects: In a Cargo workspace with multiple crates, the target/ directory is shared at the workspace root. A single /target/ pattern in the root .gitignore covers all member crates.

What to commit: Cargo.toml, Cargo.lock (for binaries), rust-toolchain.toml (specifies the Rust version), and rustfmt.toml (formatting configuration).

Use Case

A Rust team publishing both a CLI application and a shared library crate needs different Cargo.lock strategies for each, with a clear .gitignore to match.

Try It — .gitignore Generator

Open full tool