Git Worktrees
Git worktrees let you check out multiple branches in separate directories sharing one .git database. Rust developers use them for parallel PR reviews, hotfix branches, and long cargo build runs without stashing.
Recipe
# From main repo
git worktree add ../billing-api-review origin/feat/billing-tax
cd ../billing-api-review
cargo test -q
# Remove when done
cd ../billing-api
git worktree remove ../billing-api-reviewWhen to reach for this:
- Reviewing a teammate PR while mid-feature locally
- Running release build on
release/*while developing onmain - Bisecting a regression without disturbing current workspace
Working Example
git worktree list
git worktree add -b hotfix/2.5.1 ../hotfix v2.5.0
cd ../hotfix
cargo build --release
./target/release/my-service --version
git worktree prune # clean stale metadataWhat this demonstrates:
- Each worktree has its own working directory and
target/(unless shared via config) - Branch cannot be checked out twice - worktrees enforce exclusivity
pruneremoves invalid worktree records
Deep Dive
Layout Convention
~/code/billing-api/ # main development (feat/*)
~/code/billing-api-review/ # ephemeral PR checkout
~/code/billing-api-hotfix/ # production hotfix
rust-analyzer
Point editor to one worktree at a time or use multi-root workspace sparingly - each tree loads separate target/ for correct diagnostics.
Gotchas
- Same branch twice - Git refuses. Fix: create worktree on detached HEAD or different branch name.
- Forgotten worktree dirs - disk clutter. Fix:
git worktree listweekly; remove merged PR trees. - Shared
targetvia symlink - can confuse incremental builds across branches. Fix: separatetargetper tree unless intentional sccache. - Uncommitted work on remove - data loss. Fix: commit or stash before
worktree remove. - CI scripts assuming path - hard-coded cwd breaks. Fix: parameterize repo root.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
git stash | Quick context switch | Long builds to replay |
Second git clone | Complete isolation | Disk and fetch duplication |
| Docker dev container | Reproducible env | Simple review |
FAQs
How many worktrees?
Typically 2-4 active; prune beyond that.
Worktrees and submodules?
Supported; initialize submodules per worktree after add.
Bare repo pattern?
Advanced: bare central repo with all worktrees as sibling dirs.
Related
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.