How to Use go clean to Remove Build Artifacts

Cli
Use `go clean` to remove object files and cached binaries generated during the build process, effectively resetting your module's build state without touching your source code.

Use go clean to remove object files and cached binaries generated during the build process, effectively resetting your module's build state without touching your source code. By default, it deletes the go.mod cache and temporary build artifacts, but you can target specific files like the compiled binary or test cache using flags like -modcache, -testcache, or -cache.

For a standard cleanup of the current module's build artifacts (including the compiled binary and test cache), run:

go clean

If you want to remove the compiled binary specifically (e.g., myapp or myapp.exe) along with the test cache, use the -cache and -testcache flags, or specify the binary name if you built it with a custom output path. To clear the entire module cache (which can be gigabytes in size) and the build cache:

go clean -modcache -cache -testcache

If you built your application with a specific output name, such as go build -o myapp, you can remove just that binary and the cache with:

go clean -cache -testcache
rm myapp

Note that go clean does not remove the go.mod or go.sum files, nor does it delete your source code. It only targets files created by the Go toolchain. The -modcache flag is particularly useful when you suspect the module cache is corrupted or when you need to force a re-download of dependencies to ensure you have the latest versions.

For a more aggressive cleanup that removes the build cache, test cache, and module cache, but leaves your source code and go.mod intact, the command is:

go clean -cache -testcache -modcache

This is often run before a fresh build to ensure no stale artifacts interfere with compilation. If you are working in a specific directory, ensure you run the command from that directory or use the -modfile flag if you have multiple go.mod files in your workspace. Remember that go clean is idempotent; running it multiple times has no additional effect once all artifacts are removed.