Skip to content
Codewilds

Go cheat sheet

The essential Go syntax on one page. Every snippet comes from a lesson of our interactive Learn Go course — click "Practise" to write it yourself and get instant feedback.

Last updated on .

Fundamentals

Go Hello World: Your First Go Program

Write your first Go program: package main, import fmt and print with fmt.Println. Learn how a Go program is structured — it runs right in your browser.

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}
Practise: Go Hello World: Your First Go Program

Go Variables: var, := and Multiple Assignment

Declare Go variables with var and the short := syntax, assign several values at once, swap them in one line and see why unused variables don't compile.

var heroName string = "Gopher"
var level int = 1
Practise: Go Variables: var, := and Multiple Assignment

Go Data Types and Zero Values

Learn Go's basic types — int, float64, string, bool, byte and rune — type conversions, and the zero value every Go variable starts with.

var lives int = 3
var speed float64 = 2.5
var name string = "Gopher"
var ready bool = true
Practise: Go Data Types and Zero Values

Go Constants and Arithmetic Operators

Use Go constants and iota, arithmetic operators, integer division and remainder, += and ++, and the math package: Sqrt, Pow, Round and Pi.

const maxLevel = 50
const realmName = "The Gopher Isles"
Practise: Go Constants and Arithmetic Operators

Go Strings and fmt.Sprintf Formatting

Learn how Go strings work — bytes, len, indexing and slicing — use the strings package and strconv.Itoa, and format text with fmt.Sprintf verbs.

fmt.Println(len("Gopher")) // 6
fmt.Println(len("olé"))    // 4: é takes two bytes
Practise: Go Strings and fmt.Sprintf Formatting

Go if/else and switch Statements

Make decisions in Go with if, else if and else, comparison and logical operators, if with a short statement, and switch cases that never fall through.

package main

import "fmt"

func main() {
	hp := 35
	if hp <= 0 {
		fmt.Println("defeated")
	} else if hp < 50 {
		fmt.Println("wounded")
	} else {
		fmt.Println("healthy")
	}
}
Practise: Go if/else and switch Statements

Go for Loops: The Only Loop You Need

Master the Go for loop: three-part loops, while-style and infinite loops, break and continue, nested loops and range over strings and integers.

package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		fmt.Println("Round", i)
	}
}
Practise: Go for Loops: The Only Loop You Need

Functions

Go Functions: Parameters and Return Values

Write your own Go functions: parameters, return values, guard clauses, pass-by-value, exported names and doc comments, with hands-on exercises.

package main

import "fmt"

// add returns the sum of a and b.
func add(a int, b int) int {
	return a + b
}

func main() {
	total := add(2, 3)
	fmt.Println(total, add(total, 10))
}
Practise: Go Functions: Parameters and Return Values

Go Multiple Return Values and Named Results

Return several values from a Go function, skip results with _, handle failures with the (value, error) pattern and use named results.

package main

import "fmt"

// minMax returns the smaller and the larger of a and b.
func minMax(a, b int) (int, int) {
	if a < b {
		return a, b
	}
	return b, a
}

func main() {
	lo, hi := minMax(8, 3)
	fmt.Println(lo, hi)
}
Practise: Go Multiple Return Values and Named Results

Go Variadic Functions: ...T Parameters

Write Go variadic functions with ...T parameters, call them with any number of arguments, spread a slice with xs... and know when to take a slice.

package main

import "fmt"

// greetAll prints a greeting for every name it receives.
func greetAll(greeting string, names ...string) {
	fmt.Println(len(names), "names")
	for _, name := range names {
		fmt.Println(greeting + ", " + name + "!")
	}
}

func main() {
	greetAll("Hi", "Ann", "Bo")
	greetAll("Hello")
}
Practise: Go Variadic Functions: ...T Parameters

Go Closures, Function Values and defer

Use Go functions as values: function types, anonymous functions and closures. Then clean up with defer and turn a panic into an error with recover.

package main

import "fmt"

func double(n int) int {
	return n * 2
}

// apply calls f with x and returns the result.
func apply(f func(int) int, x int) int {
	return f(x)
}

func main() {
	var op func(int) int = double
	square := func(n int) int { return n * n }

	fmt.Println(op(4), apply(square, 5), apply(double, 5))
}
Practise: Go Closures, Function Values and defer

Slices & Maps

Go Arrays vs Slices: Slicing and range

Learn the difference between Go arrays and slices: fixed-size arrays, slice literals, slicing with s[low:high], shared elements and range loops.

var scores [3]int // three ints, all 0
scores[0] = 90
primes := [5]int{2, 3, 5, 7, 11}
days := [...]string{"Mon", "Tue", "Wed"} // type [3]string
fmt.Println(scores, len(primes), len(days))
Practise: Go Arrays vs Slices: Slicing and range

Go Slices: append, make, len and cap

Grow Go slices with append, preallocate them with make, understand len vs cap, copy safely, avoid the aliasing trap and use the slices package.

var loot []string // a nil slice is ready to use
loot = append(loot, "gold")
loot = append(loot, "gem", "sword") // several values at once
more := []string{"shield", "potion"}
loot = append(loot, more...) // ... spreads a slice into arguments
fmt.Println(loot, len(loot))
Practise: Go Slices: append, make, len and cap

Sorting Slices and 2D Slices in Go

Sort Go slices with sort.Ints, sort.Slice and slices.SortFunc, keep sorts stable, and build 2D slices and grids with make and nested range loops.

nums := []int{42, 7, 19, 3}
sort.Ints(nums) // sorts in place, returns nothing
fmt.Println(nums)

names := []string{"cy", "Bo", "ada", "Al"}
slices.Sort(names)
fmt.Println(names)
Practise: Sorting Slices and 2D Slices in Go

Go Maps: Create, Read, Update, Delete and comma-ok

Learn Go maps: literals and make, reading, updating and deleting keys, the comma-ok idiom, nil maps, sets and the counts[key]++ counting pattern.

prices := map[string]int{
	"sword":  120,
	"potion": 15,
}
counts := make(map[string]int) // empty and ready to use
Practise: Go Maps: Create, Read, Update, Delete and comma-ok

Structs & Methods

Go Structs: Define Your Own Types

Learn Go structs: declare struct types, create values with struct literals, use zero values, nest, copy and compare structs, and write constructors.

type Player struct {
	Name  string
	Level int
	HP    int
}
Practise: Go Structs: Define Your Own Types

Go Pointers Explained: & and *

Understand Go pointers: take an address with &, dereference with *, avoid nil pointer panics, use new and let functions change values through pointers.

package main

import "fmt"

func main() {
	score := 10
	p := &score // p has type *int: "pointer to int"

	fmt.Println(*p) // read through the pointer
	*p = 20         // write through the pointer
	fmt.Println(score)

	score++
	fmt.Println(*p)
}
Practise: Go Pointers Explained: & and *

Go Methods: Value and Pointer Receivers

Learn Go methods: attach functions to your own types, choose value or pointer receivers, call methods on values and pointers, and write a String() method.

type Circle struct {
	Radius float64
}

// Area is a method with the receiver c of type Circle.
func (c Circle) Area() float64 {
	return 3.14 * c.Radius * c.Radius
}

func (c Circle) Diameter() float64 {
	return 2 * c.Radius
}

func main() {
	c := Circle{Radius: 2}
	fmt.Println(c.Area(), c.Diameter()) // 12.56 4
}
Practise: Go Methods: Value and Pointer Receivers

Go Struct Embedding and Composition

Learn Go struct embedding: promoted fields and methods, shadowing a method, pointer receivers through embedding, and why it's composition, not inheritance.

type Animal struct {
	Name string
	Legs int
}

func (a *Animal) Describe() string {
	return fmt.Sprintf("%s has %d legs", a.Name, a.Legs)
}

type Dog struct {
	Animal // embedded: a type without a field name
	Breed  string
}

func main() {
	d := Dog{
		Animal: Animal{Name: "Rex", Legs: 4},
		Breed:  "Beagle",
	}
	fmt.Println(d.Name, d.Breed) // promoted field
	fmt.Println(d.Describe())    // promoted method
	fmt.Printf("%+v\n", d)
}
Practise: Go Struct Embedding and Composition

Interfaces & Errors

Go Interfaces: Implicit Implementation and Polymorphism

Learn Go interfaces: method sets, implicit implementation, polymorphism with slices of interfaces, pointer receivers, the empty interface any and nil.

type Shape interface {
	Area() float64
	Perimeter() float64
}
Practise: Go Interfaces: Implicit Implementation and Polymorphism

Go Type Assertions and Type Switches

Get concrete values back out of Go interfaces with type assertions, the comma-ok form and type switches, including case nil and multi-type cases.

var v any = "gopher"
s := v.(string)
fmt.Println(strings.ToUpper(s))
Practise: Go Type Assertions and Type Switches

Go Error Handling: error Values and if err != nil

Learn Go error handling: the error interface, errors.New and fmt.Errorf, returning (value, error), if err != nil checks and sentinel errors with errors.Is.

type error interface {
	Error() string
}
Practise: Go Error Handling: error Values and if err != nil

Go Custom Errors and Error Wrapping with %w

Create custom error types in Go, add context with fmt.Errorf and %w, and inspect error chains with errors.Is, errors.As, errors.Unwrap and errors.Join.

type CooldownError struct {
	Spell   string
	Seconds int
}

func (e *CooldownError) Error() string {
	return fmt.Sprintf("%s is cooling down (%ds left)", e.Spell, e.Seconds)
}

func Cast(spell string, cooldown int) error {
	if cooldown > 0 {
		return &CooldownError{Spell: spell, Seconds: cooldown}
	}
	return nil
}
Practise: Go Custom Errors and Error Wrapping with %w

Concurrency

Goroutines in Go: Lightweight Concurrency

Run functions concurrently with the go keyword, wait for goroutines with sync.WaitGroup and collect results safely. Concurrency vs parallelism in Go.

go saveScore(player) // runs in the background
go func() {          // anonymous functions work too
	fmt.Println("working...")
}()
Practise: Goroutines in Go: Lightweight Concurrency

Go Channels: Communicating Between Goroutines

Send values between goroutines with Go channels: make(chan T), send and receive, unbuffered channels, deadlocks and directional types like chan<- int.

package main

import "fmt"

func main() {
	ch := make(chan string)

	go func() {
		ch <- "ping" // send
	}()

	msg := <-ch // receive
	fmt.Println(msg)
}
Practise: Go Channels: Communicating Between Goroutines

Go Buffered Channels, close and range

Use buffered channels in Go, close a channel to signal the end of the data, receive with range and the comma-ok idiom, and build generators and pipelines.

package main

import "fmt"

func main() {
	ch := make(chan string, 2)
	ch <- "sword"
	ch <- "shield" // no receiver needed yet: the buffer has room
	fmt.Println(len(ch), cap(ch))
	fmt.Println(<-ch, <-ch)
}
Practise: Go Buffered Channels, close and range

Go select: Timeouts and Non-blocking Channels

Wait on several Go channels at once with select, add timeouts with time.After, use default for non-blocking receives and stop loops with a done channel.

package main

import (
	"fmt"
	"time"
)

func main() {
	hare := make(chan string)
	tortoise := make(chan string)
	go func() {
		time.Sleep(50 * time.Millisecond)
		tortoise <- "tortoise"
	}()
	go func() {
		time.Sleep(5 * time.Millisecond)
		hare <- "hare"
	}()

	select {
	case winner := <-hare:
		fmt.Println("first:", winner)
	case winner := <-tortoise:
		fmt.Println("first:", winner)
	}
}
Practise: Go select: Timeouts and Non-blocking Channels

Go Mutex: Protecting Shared State with sync.Mutex

Avoid data races in Go: protect shared variables and maps with sync.Mutex and RWMutex, count with sync/atomic and learn when to use channels instead.

var hits int
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
	wg.Add(1)
	go func() {
		defer wg.Done()
		hits++ // data race!
	}()
}
wg.Wait()
fmt.Println(hits)
Practise: Go Mutex: Protecting Shared State with sync.Mutex