How to Cache the Rust target Directory in GitHub Actions
Rust compiles are slow, and a cold target directory means recompiling every dependency on every run.
Cache ~/.cargo/registry, ~/.cargo/git, and target/, keyed on Cargo.lock. The community Swatinem/rust-cache action wires this up with sensible defaults.
Steps
- Check out the repo and install the toolchain.
- Add
Swatinem/rust-cache(or a manualactions/cachecovering the cargo dirs andtarget/). - Let the action key on
Cargo.lockand the compiler version automatically. - Run your
cargo buildorcargo testafter the cache restores.
Workflow
.github/workflows/rust.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --all-featuresGotchas
- A huge
target/can blow the 10 GB per-repo cache budget; cache only the workspace you test. - Changing the toolchain version should bust the cache, which
rust-cachehandles for you. - Latchkey persists the target directory between runs so Rust pipelines start warm and recover from flakes automatically.
Related guides
How to Cache Go Build and Modules in GitHub ActionsSpeed up Go CI by caching the module download cache and the build cache in GitHub Actions, keyed on go.sum so…
How to Cache the .gradle Directory in GitHub ActionsCache the Gradle user home and wrapper in GitHub Actions so Java and Kotlin builds reuse downloaded dependenc…