Here are a list of daily Go commands used by developers, which will help you stay productive if you know about them.
go get
Downloads third party packages, by git cloning the repository and installing binaries if any
Example:
# downloads the "errors" packagegogetgithub.com/pkg/errorso# downloads and updates the "errors" packagegoget-ugithub.com/pkg/errors# downloads all packages that the current project imports/usesgoget./...# downloads and updates all packages that the current project imports/usesgoget-u./...
go run
Compiles and builds the project, after which it generates a binary in a temporary location then executes that binary
Example:
go build
Compiles and creates executable binary from source code
Example:
go test
Runs all Go tests which are located inside _test.go files from current working directory
Example:
go install
Compiles Go code from binary.go and creates a binary called "bin" then places it inside $GOPATH/bin directory
In order for this to work the file need to in package main and have a main function
Example:
go fmt
Formats all Go code from current working directory
Example:
go vet
Checks for potential Go issues in current working directory
Example:
There’s an enhanced version of go fmt available called goimports that also cleans up your import statements. It puts them in alphabetical order, removes unused imports, and attempts to guess any unspecified imports.
The -l flag tells goimports to print the files with incorrect formatting to the console. The -w flag tells goimports to modify the files in-place. The . specifies the files to be scanned: everything in the current directory and all of its subdirectories.
Rather than use separate tools, you can run multiple tools together with golangci-lint. It combines golint, govet, and an ever-increasing set of other code quality tools. Once it is installed, you run golangci-lint with the command:
go env
Displays all environment variables that Go uses and their values
go help
Displays a list of all available Go commands. Have fun and play around with them
For more info about Go commands check out Go Commands
# Compiles "main.go" and executes the binary
go run main.go
# Compiles "main.go" and "package.go" and executes the binary
go run main.go package.go
# Compiles all ".go" files in CWD and executes the binary
go run *.go
go build
go build -o executable-name
go test ./...
go test -shuffle
go test -random
go test -run
go test -v