How to Use go install: Syntax, Example, and Tips
Use
go install to compile and install Go packages or commands by specifying the package path or module version. It builds the binary and places it in your Go bin directory, making it easy to run your Go programs.Syntax
The basic syntax of go install is:
go install [build flags] [packages]packagescan be a local path, module path, or package pattern.- Optionally, you can specify a version like
@latestto install a specific module version.
This command compiles the package and installs the resulting binary into your Go bin directory (usually $GOPATH/bin or $HOME/go/bin).
bash
go install [build flags] [package[@version]]
Example
This example shows how to install a Go command-line tool from a module path:
Run go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest to download, build, and install the latest version of golangci-lint. The binary will be placed in your Go bin directory.
After installation, you can run golangci-lint directly from your terminal if your Go bin directory is in your system PATH.
bash
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
Common Pitfalls
Common mistakes when using go install include:
- Not specifying a version when installing from a module path, which may cause errors in Go 1.18+.
- Expecting
go installto work likego buildwithout installing the binary. - Not having your Go bin directory in your system PATH, so installed binaries are not found.
Example of a wrong command and the correct way:
bash
go install github.com/golangci/golangci-lint/cmd/golangci-lint
# This may fail in Go 1.18+ because version is missing
# Correct usage with version:
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latestQuick Reference
Tips for using go install effectively:
- Always specify a version when installing from a module path (e.g.,
@latest). - Use
go install ./...to install all commands in the current module. - Ensure your Go bin directory is in your PATH to run installed binaries easily.
go installbuilds and installs binaries, unlikego buildwhich only builds.
Key Takeaways
Use
go install to build and install Go binaries into your Go bin directory.Specify a version (like
@latest) when installing from module paths to avoid errors.Make sure your Go bin directory is in your system PATH to run installed commands easily.
go install differs from go build by installing the binary after building.You can install multiple commands at once using patterns like
./....