How to Use go install to Install Binaries

Cli
Use `go install` to compile a package and place the resulting binary in your `$GOPATH/bin` (or `$GOBIN`) directory, which is typically added to your system PATH.

Use go install to compile a package and place the resulting binary in your $GOPATH/bin (or $GOBIN) directory, which is typically added to your system PATH. This command fetches dependencies, builds the code, and installs the executable without creating any source files in your current working directory.

For a standard package like golang.org/x/tools/cmd/goimports, run the following command to install the latest version:

go install golang.org/x/tools/cmd/goimports@latest

This downloads the module, builds the binary, and places it in your $GOBIN directory. You can then run goimports directly from any terminal. If you need to install a specific version instead of the latest, replace @latest with the version tag, such as @v0.6.0.

To install a binary from a local repository or a specific branch, specify the path and the branch name. For example, to install a tool from a local project at github.com/youruser/mytool using the main branch:

go install github.com/youruser/mytool/cmd/mytool@main

Ensure your $GOBIN directory is in your system's PATH environment variable so the installed binaries are accessible globally. You can verify your current GOBIN setting by running go env GOBIN. If it is empty, Go defaults to $GOPATH/bin. To set a custom installation directory, export the GOBIN variable before running the install command:

export GOBIN=$HOME/.local/bin
go install github.com/youruser/mytool/cmd/mytool@main

Remember that go install only installs the binary; it does not modify your local source code or create a go.mod file in your current directory. It is the standard method for distributing Go command-line tools. If you encounter permission errors, ensure your $GOBIN directory exists and is writable. For older Go versions (prior to 1.16), you might need to specify the module path explicitly, but in modern Go, the @version syntax handles dependency resolution automatically.