glunty

Go Language Cheat Sheet

A searchable reference of common Go language snippets and what each one does.

Common Go language snippets with a plain-English description of what each one does
Snippet What it does
package main Declare the package name; an executable program must use package main.
import "fmt" Import a standard library package so its exported functions are available.
func main() {} Define the program entry point where execution begins.
var x int = 5 Declare a variable with an explicit type and an initial value.
var x = 5 Declare a variable and let Go infer its type from the value.
x := 5 Short declaration that declares and infers a variable inside a function.
const Pi = 3.14 Declare a compile-time constant that cannot be reassigned.
fmt.Println("hello") Print the arguments followed by a newline to standard output.
fmt.Printf("%d\n", n) Print using format verbs such as %d, %s, or %v.
var active bool = true A bool variable holds either true or false.
var ratio float64 = 1.5 A float64 variable holds a 64-bit floating-point number.
const ( A = iota; B; C ) iota generates successive untyped integer constants 0, 1, 2 in a block.
var a [3]int Declare a fixed-size array of three ints; the length is part of the type.
a := [3]int{1, 2, 3} Create and initialize a fixed-size array with three values.
var s []int Declare a slice, a dynamically sized view over an array.
s := []int{1, 2, 3} Create a slice with three initial elements.
s := make([]int, 0, 10) Allocate a slice with a starting length and a capacity.
s = append(s, 4) Add one or more elements to a slice, growing it as needed.
var m map[string]int Declare a map from string keys to int values; it is nil until made.
m := map[string]int{"a": 1} Create and initialize a map with one key and value.
m := make(map[string]int) Allocate an empty map that is ready to use.
len(s) Return the number of elements in a slice, array, map, or string.
cap(s) Return the capacity of a slice before it must grow again.
for i, v := range s {} Loop over a slice getting each index and its value.
for k, v := range m {} Loop over a map getting each key and its value.
delete(m, "a") Remove a key and its value from a map.
if x > 0 {} Run a block only when the condition is true.
if v := f(); v > 0 {} Run a short statement, then test it; v is scoped to the if.
if x > 0 {} else {} Choose between two blocks based on the condition.
for i := 0; i < n; i++ {} The classic three-part loop with init, condition, and post.
for x < 10 {} Use for with only a condition to act as a while loop.
for {} Loop forever until a break or return stops it.
for _, v := range items {} Loop over a collection ignoring the index with the blank identifier.
switch x { case 1: } Branch on a value; Go cases do not fall through by default.
switch { case x > 0: } A conditionless switch reads like a clean if-else chain.
break Exit the innermost for, switch, or select immediately.
continue Skip to the next iteration of the innermost loop.
defer f.Close() Schedule a call to run when the surrounding function returns.
func add(a, b int) int {} Define a function taking two ints and returning an int.
func divmod(a, b int) (int, int) {} Return more than one value from a single function.
func split() (x, y int) {} Name the results so a bare return sends them back.
func sum(nums ...int) int {} A variadic parameter accepts any number of trailing arguments.
inc := func(n int) int { return n + 1 } An anonymous function that closes over variables in scope.
var f func(int) int = double Functions are values you can assign and pass around.
type Point struct { X, Y int } Define a composite type that groups named fields.
p := Point{X: 1, Y: 2} Create a struct value using named fields.
func (p Point) Sum() int {} Attach a method to a type through a value receiver.
func (p *Point) Move() {} A pointer receiver lets the method modify the struct.
type Stringer interface { String() string } Define a set of method signatures a type must satisfy.
type Admin struct { User } Embed one struct in another to reuse its fields and methods.
p := new(Point) Allocate a zeroed value and return a pointer to it.
go doWork() Start a function running concurrently as a goroutine.
ch := make(chan int) Create an unbuffered channel that carries int values.
ch <- 1; v := <-ch Send a value into a channel and receive one from it.
select { case v := <-ch: } Wait on several channel operations and run whichever is ready.
ch := make(chan int, 5) A buffered channel lets sends proceed until the buffer is full.
var wg sync.WaitGroup Wait for a group of goroutines using Add, Done, and Wait.
var mu sync.Mutex Guard shared data with Lock and Unlock to avoid data races.
close(ch) Close a channel to signal that no more values will be sent.
func f() error {} error is a built-in interface returned to signal failure.
errors.New("boom") Create a simple error value with a fixed message.
fmt.Errorf("bad: %w", err) Build a formatted error and wrap another with the %w verb.
if err != nil { return err } The standard check that handles or passes on an error.
panic("unreachable") Stop normal flow and start unwinding the stack.
recover() Regain control inside a deferred function after a panic.

Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.

What this tool does

This is a searchable quick reference for the Go syntax you reach for every day, from declaring variables and writing functions to slices, maps, structs, goroutines, and error handling. Each row pairs a short Go snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one topic. The whole list is built into the page, so it works offline and sends nothing anywhere.

How to use it

Start typing in the Filter box. Entering slice surfaces the slice and append rows; entering range shows the loop forms; entering chan brings up the channel snippets. The category buttons (Basics, Collections, Control flow, Functions, Structs and interfaces, Concurrency, Errors) narrow the table to one topic and combine with the text filter, so you can pick Concurrency and type sync to zero in on WaitGroup and Mutex. Clear the box to see the full sheet again.

Common use cases

  • Recalling the exact syntax for something you use rarely, like a variadic parameter or a pointer receiver.
  • Copying a correct snippet into your editor instead of guessing at the shape.
  • Teaching a teammate the difference between an array and a slice.
  • Checking how to start a goroutine or read a value from a channel.
  • Reviewing core Go syntax before an interview or a new project.

Common pitfalls

  • Writing to a nil map. Reading from a nil map is safe, but writing to one panics at run time. Create the map with make before you assign any keys.
  • Loop variable capture. Older Go versions reused a single loop variable across iterations, so closures could all observe the final value. Capture it into a local copy if you target an older toolchain.
  • Value versus pointer receivers. A method with a value receiver works on a copy, so changes do not persist. Use a pointer receiver when the method needs to modify the original struct.
  • Unbuffered channel deadlocks. A send on an unbuffered channel blocks until another goroutine receives. Forgetting to run that receiver hangs the whole program.

Frequently asked questions

What does the := operator do in Go?
The := operator is short variable declaration. It declares one or more new variables and infers their types from the values on the right, so x := 5 creates an int named x. It only works inside a function, not at package level, where you must use var instead. At least one variable on the left must be new, which lets you reuse := to assign to existing variables alongside a fresh one.
How do slices differ from arrays in Go?
An array has a fixed length that is part of its type, so [3]int and [4]int are different types and the size can never change. A slice is a lightweight view onto an underlying array: it has a length and a capacity, can grow with append, and is what almost all Go code uses in practice. Passing an array copies every element, while passing a slice copies only a small header that still points at the same backing data.
What is a goroutine?
A goroutine is a function running concurrently, managed by the Go runtime rather than the operating system. You start one by writing go before a function call, and it is far cheaper than a thread, so a program can run thousands at once. Goroutines usually communicate by sending values over channels instead of sharing memory directly, which is at the heart of the Go concurrency model.
How does Go handle errors?
Go treats errors as ordinary values rather than exceptions. Functions that can fail return an error as their last result, and the caller checks it with the standard if err != nil pattern before continuing. You create errors with errors.New or fmt.Errorf, and fmt.Errorf with the %w verb wraps an underlying error so callers can inspect it later. panic and recover exist for truly exceptional situations, not routine failures.
What is a pointer receiver and when should I use one?
A method can be defined on a value receiver or a pointer receiver. A pointer receiver, written as func (p *Point) Move(), lets the method modify the original value and avoids copying a large struct on every call. Use a pointer receiver when the method changes the receiver or when the struct is big, and a value receiver for small, immutable types. As a rule of thumb, keep all methods on a given type consistent rather than mixing the two.
Does this cheat sheet send my searches anywhere?
No. The entire snippet list is baked into the page and every search and filter runs in your browser with JavaScript, so nothing you type leaves your device. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.

Embed this tool

Free for any use; attribution appreciated. Paste this on your site:

The embed runs the same tool that lives at this URL. No tracking; no ads inside the embed. Resize height as needed for your layout.

Cite this tool

For academic, journalistic, or technical references. Pick a format:

Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.

Embedded tool from glunty.com