Go Cheatsheet
Go is a compiled language with a small standard library, fast builds, and first-class tools for formatting and testing.
Learn modules, clear error handling, and goroutines early—they show up in almost every Go codebase.
Full lessons: Go Tutorials
Basics
Hello package
Every file belongs to a package. main with func main is an executable.
package main
import "fmt"
func main() {
fmt.Println("Hello")
}
Variables
Use := inside functions for short declarations; var elsewhere or for zero values.
x := 10
var name string = "Ada"
Constants
Declare with const. Untyped constants are flexible until used.
const Pi = 3.14159
go run / build
Run without installing, or build a binary.
go run .
go build -o app .
gofmt / go test
Format with gofmt (or via go fmt). Test packages with go test.
go fmt ./...
go test ./...
Types & composites
Structs
Group fields into a named type.
type User struct {
ID int
Name string
}
Slices
Dynamic views over arrays. Prefer slices over arrays in APIs.
nums := []int{1, 2, 3}
nums = append(nums, 4)
Maps
Key/value lookups. Check the second return value for presence.
m := map[string]int{"a": 1}
v, ok := m["a"]
Pointers
Hold the address of a value. Methods often use pointer receivers to mutate.
p := &User{Name: "Ada"}
fmt.Println(p.Name)
Functions & errors
Multiple returns
Return a result and an error—the standard Go pattern.
func half(n int) (int, error) {
if n%2 != 0 {
return 0, fmt.Errorf("odd: %d", n)
}
return n / 2, nil
}
Check errors
Handle errors immediately; do not ignore with blank identifier casually.
v, err := half(4)
if err != nil {
return err
}
Defer
Schedule a call to run when the function returns—great for Close.
f, err := os.Open("f.txt")
if err != nil { return err }
defer f.Close()
Methods
Functions with a receiver type.
func (u User) Greet() string {
return "Hi, " + u.Name
}
Modules & concurrency
go.mod
Modules define the module path and dependencies.
go mod init example.com/app
go get rsc.io/quote
Goroutines
Start concurrent work with go. Coordinate with channels or sync tools.
go func() {
fmt.Println("async")
}()
Channels
Send and receive between goroutines.
ch := make(chan string, 1)
ch <- "hi"
msg := <-ch
Context peek
Pass context.Context for cancellation and deadlines in libraries and servers.
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
Comments
One comment per signed-in account. Comments are saved with this page’s URL.