How to Cache Rust Dependencies and the Target Dir in GitHub Actions
The rust-cache action caches the cargo registry and target/ keyed on Cargo.lock, skipping unchanged compiles.
Use Swatinem/rust-cache after installing the toolchain. It caches ~/.cargo and target/ with a smart key, and prunes stale build artifacts automatically.
Cache the cargo home and target
The action keys on Cargo.lock and the toolchain, so only changed crates recompile.
.github/workflows/ci.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: ci
- run: cargo build --release
- run: cargo testGotchas
- Caching the whole
target/naively bloats the cache;rust-cacheprunes intermediate artifacts so it stays usable - prefer it over a rawactions/cache. - A
shared-keylets multiple jobs share one cache; omit it and each job key diverges, lowering hit rate. - The cache is invalidated on toolchain or
Cargo.lockchanges - expect a full recompile after a dependency bump.
Related guides
How to Cache Rust Dependencies and the Target Dir in GitLab CICache Rust dependencies and the target dir in GitLab CI by redirecting CARGO_HOME into the project dir and ca…
How to Cache Go Modules and Build Cache in GitHub ActionsCache Go modules and the Go build cache in GitHub Actions - let actions/setup-go cache go.sum, or cache ~/go/…