Part 1 — The language · wrap-up
Cheat sheet & self-check
Every command from this section on one page.
Every day
go mod init github.com/me/kaudit | Start a module (the import path of your project) |
go run . | Compile and run the package in this folder |
go build -o bin/kaudit . | Build a binary |
go test ./... | Run all tests in the module |
go vet ./... && gofmt -l . | Static checks and unformatted files |
go get k8s.io/client-go@v0.34.0 | Add or change a dependency version |
go mod tidy | Add missing and remove unused dependencies |
Build for elsewhere
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o kaudit-arm64 . | Static Linux binary for ARM64, from any machine |
go build -ldflags='-s -w -X main.version=1.2.0' . | Smaller binary, version stamped at build time |
go env GOPATH GOCACHE | Where modules and build cache live |
Syntax at a glance
x := 3 | Declare and assign (type inferred) inside functions |
var nodes []string | Declare with the zero value (nil slice, ready to append) |
nodes = append(nodes, "n1") | Add to a slice |
counts := map[string]int{} | Empty map ready to use |
for i, n := range nodes { } | Loop over a slice with index and value |
if v, ok := counts["n1"]; ok { } | Read a map key and check it exists |
type Node struct { Name string; Ready bool } | Define a struct |
func (n Node) String() string { } | A method on a type |
Patterns
if err != nil { return fmt.Errorf("read %s: %w", path, err) } | Add context and keep the original error |
if errors.Is(err, os.ErrNotExist) { } | Is it (or does it wrap) this specific error? |
var nf *NotFoundError; if errors.As(err, &nf) { } | Is it (or does it wrap) this error type? Get it |
defer f.Close() | Run clean-up when the function returns, whatever path it takes |
var ErrNoNodes = errors.New("no nodes") | A sentinel error callers can test for |