Skip to content

Go Language Cheatsheet

A complete Go (Golang) programming language cheatsheet from beginner to advanced — syntax, types, concurrency, interfaces, generics, error handling, modules, testing, and best practices.

Go (also called Golang) is a statically typed, compiled systems language created at Google. It emphasizes simplicity, fast compilation, built-in concurrency, and efficient garbage collection. It is widely used for backend services, CLI tools, cloud infrastructure, and networking.

This cheatsheet covers beginner fundamentals through advanced topics.

Terminal window
# Install (official)
# https://go.dev/dl/
# Version
go version
# Environment
go env
# New module
mkdir myproject && cd myproject
go mod init example.com/myproject
# Run
go run main.go
# Build
go build -o myapp
# Install binary
go install
# Test
go test ./...
# Format & vet
go fmt ./...
go vet ./...
# Tidy dependencies
go mod tidy

go.mod example:

module example.com/myproject
go 1.23
require (
github.com/some/package v1.2.3
)

package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
  • Every file belongs to a package.
  • main package + main function = executable.
  • Exported names start with a capital letter (Fmt vs fmt).

var x int = 10
var y = 20 // type inferred
z := 30 // short declaration (inside functions)
var a, b int = 1, 2
var (
name string = "Alice"
age int = 30
)

const Pi = 3.14159
const (
StatusOK = 200
StatusError = 500
)
// iota for enums
const (
Red = iota // 0
Green // 1
Blue // 2
)

Type Description
bool true / false
string immutable sequence of bytes
int, int8…int64 signed integers
uint, uint8…uint64 unsigned integers
byte alias for uint8
rune alias for int32 (Unicode code point)
float32, float64 floating point
complex64, complex128 complex numbers
uintptr integer large enough for a pointer

var i int // 0
var f float64 // 0
var b bool // false
var s string // ""
var p *int // nil

i := 42
f := float64(i)
u := uint(f)

// if
if x > 0 {
// ...
} else if x == 0 {
// ...
} else {
// ...
}
// if with short statement
if err := doSomething(); err != nil {
return err
}
// switch (no fallthrough by default)
switch day {
case "Mon", "Tue":
fmt.Println("weekday")
case "Sat", "Sun":
fmt.Println("weekend")
default:
fmt.Println("other")
}
// type switch
switch v := x.(type) {
case int:
fmt.Printf("int: %d\n", v)
case string:
fmt.Printf("string: %s\n", v)
default:
fmt.Println("unknown")
}
// for (only loop construct)
for i := 0; i < 10; i++ { }
for condition { } // while-style
for { } // infinite
for index, value := range slice { }
for key, value := range map { }
for index, runeValue := range str { } // iterates runes

break, continue, and labeled statements work as expected.

func add(a, b int) int {
return a + b
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Named return values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // naked return
}
// Variadic
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Function values & closures
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}

func main() {
defer fmt.Println("world") // runs at end of function
fmt.Println("hello")
}
// Common pattern: cleanup
f, err := os.Open("file.txt")
if err != nil {
return err
}
defer f.Close()
// Panic & recover
func mayPanic() {
panic("something went wrong")
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
mayPanic()
}

Prefer returning errors over panicking in library code.

i := 42
p := &i // pointer to i
fmt.Println(*p) // read through pointer
*p = 21 // write through pointer
// Go has no pointer arithmetic
// New allocates and returns pointer
p := new(int)
*p = 10

Structs are often passed by pointer to avoid copying and to allow mutation.

var a [3]int = [3]int{1, 2, 3}
b := [...]int{4, 5, 6} // size inferred

s := []int{1, 2, 3, 4, 5}
s = append(s, 6)
s = append(s, 7, 8, 9)
// Slicing
t := s[1:4] // [2 3 4]
u := s[:3] // [1 2 3]
v := s[2:] // [3 4 5 6 ...]
// make
s = make([]int, 5) // length 5, capacity 5
s = make([]int, 0, 10) // length 0, capacity 10
// copy
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src)
// length & capacity
len(s)
cap(s)

Important: Slices share underlying arrays. Be careful with mutations and append.

m := make(map[string]int)
m["alice"] = 30
m["bob"] = 25
age, ok := m["carol"] // ok = false if missing
delete(m, "bob")
// literal
m = map[string]int{
"alice": 30,
"bob": 25,
}
for k, v := range m {
fmt.Println(k, v)
}

Maps are reference types; concurrent access requires synchronization.

type Person struct {
Name string
Age int
}
p := Person{Name: "Alice", Age: 30}
p := Person{"Alice", 30} // positional
p := Person{Name: "Alice"} // Age = 0
// Pointer receiver vs value receiver
func (p Person) Greet() string { // value receiver
return "Hello, " + p.Name
}
func (p *Person) Birthday() { // pointer receiver
p.Age++
}
// Embedding (composition)
type Employee struct {
Person
Salary float64
}
e := Employee{
Person: Person{Name: "Bob", Age: 28},
Salary: 75000,
}
fmt.Println(e.Name) // promoted field

type Speaker interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string { return "Woof" }
type Cat struct{}
func (c Cat) Speak() string { return "Meow" }
func saySomething(s Speaker) {
fmt.Println(s.Speak())
}
saySomething(Dog{})
saySomething(Cat{})
  • Interfaces are satisfied implicitly (no implements keyword).
  • Empty interface: interface{} or any (Go 1.18+).
  • Type assertion: v, ok := i.(Type)
  • Type switch shown earlier.

Common interfaces: error, fmt.Stringer, io.Reader, io.Writer, sort.Interface.

import "errors"
import "fmt"
var ErrNotFound = errors.New("not found")
func find(id int) (string, error) {
if id < 0 {
return "", fmt.Errorf("invalid id: %d", id)
}
if id == 0 {
return "", ErrNotFound
}
return "item", nil
}
// Checking
result, err := find(42)
if err != nil {
if errors.Is(err, ErrNotFound) {
// handle specifically
}
return err
}
// Wrapping (Go 1.13+)
return fmt.Errorf("failed to process: %w", err)
// Unwrap
errors.Unwrap(err)

Go does not have exceptions. Errors are values.

go func() {
fmt.Println("running concurrently")
}()
go doWork()

Very lightweight; the runtime multiplexes them onto OS threads.

ch := make(chan int) // unbuffered
ch := make(chan int, 10) // buffered
// send / receive
ch <- 42
value := <-ch
// close
close(ch)
// range over channel
for v := range ch {
fmt.Println(v)
}
// select (multiplex)
select {
case msg := <-ch1:
fmt.Println("from ch1:", msg)
case ch2 <- 42:
fmt.Println("sent to ch2")
case <-time.After(1 * time.Second):
fmt.Println("timeout")
default:
fmt.Println("no communication")
}

// Worker pool
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// Fan-out / fan-in, pipelines, context cancellation...

import "sync"
var mu sync.Mutex
mu.Lock()
// critical section
mu.Unlock()
var once sync.Once
once.Do(func() { /* runs only once */ })
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// work
}()
wg.Wait()

Prefer channels for communication; use mutexes for protecting shared state.

func Min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
item := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return item, true
}

Use constraints package or define your own type sets.

  • Package name = last element of import path by convention.
  • Only capitalized identifiers are exported.
  • Internal packages: put under internal/ directory.
  • Versioning follows semantic import versioning (/v2 for major version 2+).
import (
"fmt"
"math/rand"
"example.com/myproject/utils"
alias "example.com/other/pkg"
)

math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
got := Add(2, 3)
if got != 5 {
t.Errorf("Add(2, 3) = %d; want 5", got)
}
}
func TestAddTable(t *testing.T) {
tests := []struct {
a, b, want int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tt := range tests {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
}
}
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(2, 3)
}
}
// Example function (shown in docs)
func ExampleAdd() {
fmt.Println(Add(1, 2))
// Output: 3
}
Terminal window
go test
go test -v
go test -cover
go test -bench=.
go test -race # race detector

import "context"
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
ctx = context.WithValue(ctx, key, value)
select {
case <-ctx.Done():
return ctx.Err()
case result := <-doWork(ctx):
// use result
}

Pass context.Context as the first parameter of functions that do I/O or may be cancelled.

Package Purpose
fmt Formatted I/O
os OS functionality
io I/O primitives
bufio Buffered I/O
net/http HTTP client & server
encoding/json JSON marshal/unmarshal
time Time and duration
strings String manipulation
strconv String conversions
errors Error creation & inspection
sync Synchronization primitives
context Cancellation & deadlines
log / log/slog Logging
testing Testing & benchmarking
flag Command-line flags
path/filepath File path utilities
crypto/... Cryptography
database/sql Database access

Error handling

if err != nil {
return fmt.Errorf("operation failed: %w", err)
}

Constructor functions

func NewServer(addr string) *Server {
return &Server{Addr: addr}
}

Functional options

type Option func(*Server)
func WithTimeout(d time.Duration) Option {
return func(s *Server) { s.Timeout = d }
}
func NewServer(addr string, opts ...Option) *Server {
s := &Server{Addr: addr}
for _, opt := range opts {
opt(s)
}
return s
}

Avoid

  • Naked returns in long functions
  • Ignoring errors (_ = someFunc())
  • Global mutable state
  • Premature optimization
  • Large interfaces (prefer small ones)

Prefer

  • Composition over inheritance
  • Explicit error returns
  • Clear package boundaries
  • gofmt / goimports always
  • Table-driven tests
  • Context for cancellation

// JSON
data, err := json.Marshal(person)
err = json.Unmarshal(data, &person)
// HTTP server
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
// HTTP client
resp, err := http.Get("https://example.com")
defer resp.Body.Close()
// Time
time.Now()
time.Sleep(1 * time.Second)
t.Format(time.RFC3339)
// String builder
var b strings.Builder
b.WriteString("hello")
s := b.String()


This cheatsheet targets modern Go (1.21+ with generics and improved standard library). Always verify against the version you are using.

You're offline Check your connection.