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.
# Install (official)# https://go.dev/dl/
# Versiongo version
# Environmentgo env
# New modulemkdir myproject && cd myprojectgo mod init example.com/myproject
# Rungo run main.go
# Buildgo build -o myapp
# Install binarygo install
# Testgo test ./...
# Format & vetgo fmt ./...go vet ./...
# Tidy dependenciesgo mod tidygo.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. mainpackage +mainfunction = executable.- Exported names start with a capital letter (
Fmtvsfmt).
var x int = 10var y = 20 // type inferredz := 30 // short declaration (inside functions)
var a, b int = 1, 2var ( name string = "Alice" age int = 30)const Pi = 3.14159const ( StatusOK = 200 StatusError = 500)
// iota for enumsconst ( 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 // 0var f float64 // 0var b bool // falsevar s string // ""var p *int // nili := 42f := float64(i)u := uint(f)// ifif x > 0 { // ...} else if x == 0 { // ...} else { // ...}
// if with short statementif 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 switchswitch 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-stylefor { } // infinite
for index, value := range slice { }for key, value := range map { }for index, runeValue := range str { } // iterates runesbreak, continue, and labeled statements work as expected.
func add(a, b int) int { return a + b}
// Multiple return valuesfunc divide(a, b float64) (float64, error) { if b == 0 { return 0, fmt.Errorf("division by zero") } return a / b, nil}
// Named return valuesfunc split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return // naked return}
// Variadicfunc sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total}
// Function values & closuresfunc 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: cleanupf, err := os.Open("file.txt")if err != nil { return err}defer f.Close()
// Panic & recoverfunc 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 := 42p := &i // pointer to ifmt.Println(*p) // read through pointer*p = 21 // write through pointer
// Go has no pointer arithmetic// New allocates and returns pointerp := new(int)*p = 10Structs 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 inferreds := []int{1, 2, 3, 4, 5}s = append(s, 6)s = append(s, 7, 8, 9)
// Slicingt := s[1:4] // [2 3 4]u := s[:3] // [1 2 3]v := s[2:] // [3 4 5 6 ...]
// makes = make([]int, 5) // length 5, capacity 5s = make([]int, 0, 10) // length 0, capacity 10
// copysrc := []int{1, 2, 3}dst := make([]int, len(src))copy(dst, src)
// length & capacitylen(s)cap(s)Important: Slices share underlying arrays. Be careful with mutations and append.
m := make(map[string]int)m["alice"] = 30m["bob"] = 25
age, ok := m["carol"] // ok = false if missingdelete(m, "bob")
// literalm = 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} // positionalp := Person{Name: "Alice"} // Age = 0
// Pointer receiver vs value receiverfunc (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 fieldtype 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
implementskeyword). - Empty interface:
interface{}orany(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}
// Checkingresult, 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)
// Unwraperrors.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) // unbufferedch := make(chan int, 10) // buffered
// send / receivech <- 42value := <-ch
// closeclose(ch)
// range over channelfor 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 pooljobs := 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.Mutexmu.Lock()// critical sectionmu.Unlock()
var once sync.Onceonce.Do(func() { /* runs only once */ })
var wg sync.WaitGroupwg.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 (
/v2for major version 2+).
import ( "fmt" "math/rand"
"example.com/myproject/utils" alias "example.com/other/pkg")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}go testgo test -vgo test -covergo test -bench=.go test -race # race detectorimport "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/goimportsalways- Table-driven tests
- Context for cancellation
// JSONdata, err := json.Marshal(person)err = json.Unmarshal(data, &person)
// HTTP serverhttp.HandleFunc("/", handler)log.Fatal(http.ListenAndServe(":8080", nil))
// HTTP clientresp, err := http.Get("https://example.com")defer resp.Body.Close()
// Timetime.Now()time.Sleep(1 * time.Second)t.Format(time.RFC3339)
// String buildervar b strings.Builderb.WriteString("hello")s := b.String()- Official: https://go.dev
- Tour: https://go.dev/tour
- Spec: https://go.dev/ref/spec
- Effective Go: https://go.dev/doc/effective_go
- Go Blog: https://go.dev/blog
- Standard library docs: https://pkg.go.dev/std
- Modules: https://go.dev/ref/mod
This cheatsheet targets modern Go (1.21+ with generics and improved standard library). Always verify against the version you are using.