Essential go
Commands
Go toolchain includes commands that help developers build, test, run, format, and vet their code easily.
1. go run
Purpose: Compile and run Go code directly.
go run main.go
This command compiles and immediately runs the Go program.
It's also possible to run multiple files:
go run main.go utils.go
2. go build
Purpose: Compile Go code and generate executable binary.
go build
This compiles the packages in the current directory and produces an executable file(file name will be the package name). You can also build specific files:
go build main.go
To cross-compile for other OS or architectures:
GOOS=linux GOARCH=amd64 go build -o myapp-linux
3. go fmt
Purpose: Format your Go code according to official style guidelines.
go fmt
This formats all Go files in the current directory. You can also target specific files:
go fmt main.go
Tip: Run this before every commit. It will keep your code consistent and readable.
4. go vet
Purpose: Analyze code and report suspicious constructs.
go vet
go vet
acts like a linter—it doesn’t check formatting but looks for bugs and bad practices, such as:
- Unreachable code
- Mismatched formatting verbs in
fmt.Printf
- Unused struct fields
- Unkeyed struct literals
It's a must-use command for catching potential issues early.
5. go test
Purpose: Run unit tests.
go test
By default, it runs tests in the current package. You can also include verbose output:
go test -v
Run tests recursively in sub-packages:
go test ./...
6. go mod
Purpose: Manage Go modules (dependency management).
Initialize a module:
go mod init github.com/yourusername/yourproject
Download dependencies:
go mod tidy
View your module's dependencies:
go list -m all
7. go get
Purpose: Add or update module dependencies.
go get github.com/gin-gonic/gin
Can be used for adding new packages or upgrading existing ones. For example, to update to the latest version:
go get -u github.com/gin-gonic/gin
8. go clean
Purpose: Remove object files and cached build files.
go clean
Can be used to clean up compiled binaries, test results and so on.
9. go doc
Purpose: Show documentation for a package/function/type.
go doc fmt
go doc fmt.Println
A helpful way to quickly reference documentation without opening a browser.
10. Check if memory is on the Heap or Stack
Purpose: Use escape analysis
to see if variables are heap-allocated.
go run -gcflags="-m" main.go
Can be used with go build
as well if we want to check without running program.
go build -gcflags="-m" main.go
Cheers 👯♀️