Menu

Go Cheat Sheet

Last updated

Hello World & program structure

Every Go program lives in a package; the entry point is func main in package main.

OperationSyntax
Package declarationpackage main
Import a packageimport "fmt"
Import multiple packagesimport (\n "fmt"\n "os"\n)
Entry pointfunc main() { ... }
Print a linefmt.Println("Hello, World!")
Formatted printfmt.Printf("%d items\n", n)
Run a filego run main.go
Build a binarygo build

Variables & types

Go is statically typed but can infer types with :=.

OperationSyntax
Declare with typevar age int = 30
Declare with inferencevar name = "Ada"
Short declarationcount := 0
Multiple at oncex, y := 1, 2
Constantconst Pi = 3.14
Zero values0, "", false, nil
Basic typesint, float64, string, bool, byte, rune
Type conversionf := float64(i)

Control flow

Go has one loop keyword - for - and no parentheses around conditions.

OperationSyntax
If / elseif x > 0 { ... } else { ... }
If with init statementif v, ok := m[k]; ok { ... }
For loop (C-style)for i := 0; i < 10; i++ { ... }
While-style loopfor x < 100 { ... }
Infinite loopfor { ... }
Range over a slicefor i, v := range items { ... }
Switchswitch day { case 1: ...; default: ... }
Switch with no expressionswitch { case x > 0: ... }
Break / continuebreak, continue

Functions

Functions are first-class values and can return multiple results.

OperationSyntax
Basic functionfunc add(a int, b int) int { return a + b }
Shared param typefunc add(a, b int) int { ... }
Multiple return valuesfunc divmod(a, b int) (int, int) { return a / b, a % b }
Named return valuesfunc split(sum int) (x, y int) { x = sum / 2; return }
Variadic functionfunc sum(nums ...int) int { ... }
Anonymous functionf := func() { ... }
Closurefunc counter() func() int { ... }
Defer (runs on return)defer file.Close()

Slices & arrays

Arrays have a fixed size; slices are dynamic views over arrays.

OperationSyntax
Fixed-size arrayvar a [3]int
Slice literalnums := []int{1, 2, 3}
Make a slices := make([]int, 0, 10)
Appends = append(s, 4)
Length / capacitylen(s), cap(s)
Slice a slices[1:3]
Copycopy(dst, src)
Iteratefor i, v := range s { ... }

Maps

Maps are Go's built-in hash tables.

OperationSyntax
Make a mapm := make(map[string]int)
Map literalm := map[string]int{"a": 1, "b": 2}
Set a valuem["c"] = 3
Get a valuev := m["a"]
Check existencev, ok := m["x"]
Delete a keydelete(m, "a")
Lengthlen(m)
Iteratefor k, v := range m { ... }

Structs & methods

Structs group fields; methods attach behavior via a receiver.

OperationSyntax
Define a structtype Point struct { X, Y int }
Create an instancep := Point{X: 1, Y: 2}
Access a fieldp.X
Pointer to a structp := &Point{1, 2}
Value receiver methodfunc (p Point) Dist() float64 { ... }
Pointer receiver methodfunc (p *Point) Move(dx int) { p.X += dx }
Embedded structtype Circle struct { Point; R int }
Struct tagsName string with a backtick-quoted json:"name" tag

Interfaces

Interfaces are satisfied implicitly - any type with the right methods qualifies.

OperationSyntax
Define an interfacetype Shape interface { Area() float64 }
Implement (implicit)func (c Circle) Area() float64 { ... }
Empty interface (any)var x interface{} or var x any
Type assertions, ok := x.(string)
Type switchswitch v := x.(type) { case int: ... }
Stringer interfacefunc (p Point) String() string { ... }

Goroutines & channels

Goroutines are lightweight threads; channels pass values between them.

OperationSyntax
Start a goroutinego doWork()
Make a channelch := make(chan int)
Buffered channelch := make(chan int, 5)
Send to a channelch <- 42
Receive from a channelv := <-ch
Close a channelclose(ch)
Range over a channelfor v := range ch { ... }
Select on channelsselect { case v := <-ch: ...; default: ... }
Wait groupvar wg sync.WaitGroup; wg.Add(1); wg.Wait()
Mutexvar mu sync.Mutex; mu.Lock(); mu.Unlock()

Error handling

Go returns errors as values - there are no exceptions.

OperationSyntax
Return an errorfunc read() (string, error) { return "", err }
Check an errorif err != nil { return err }
Create an errorerrors.New("not found")
Formatted errorfmt.Errorf("bad id %d", id)
Wrap an errorfmt.Errorf("load: %w", err)
Unwrap / matcherrors.Is(err, os.ErrNotExist)
Match by typeerrors.As(err, &target)
Panic / recoverdefer func() { recover() }()

The Go syntax you reach for most, on one page. This Go cheat sheet is a quick reference for the core language - variables and types, slices and maps, structs and interfaces, plus the goroutines and channels that make Golang shine at concurrency.

Everything here is standard Go and compiles with the official toolchain. Copy what you need, or try every snippet live in the Go playground - no install required.

Go cheat sheet FAQ

Is this Go cheat sheet free?
Yes. This Go cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a slice operation, channel pattern, or struct method.
What is the difference between := and var in Go?
var x = 0 declares a variable and works anywhere, including at package level. x := 0 is short variable declaration: it both declares and assigns, infers the type, and can only be used inside a function. Use var when you need an explicit type or a package-level variable, and := for concise local declarations.
What are goroutines and channels?
A goroutine is a lightweight thread managed by the Go runtime - you start one by writing go someFunc(). Channels are typed pipes that let goroutines communicate safely: one goroutine sends with ch <- v and another receives with <-ch. Together they are Go's core concurrency model, captured by the saying "share memory by communicating."
Can I practice Go online?
Yes. Open the Go playground to run any snippet from this cheat sheet in your browser - no Go toolchain to install. When you want structure, Coddy's free interactive Go course takes you from variables and slices to goroutines and channels step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (variables, control flow, functions) down to advanced ones (goroutines, channels, error handling), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn Go with Coddy

GET STARTED