Go Cheat Sheet

By Syncfusion®, Inc. · Last updated

A lookup page for the whole course: one table per topic, from data types and keywords to files, JSON, goroutines and context.

What Is This Page?

Reference page = a page you look things up in, not one you read from top to bottom.

Nobody remembers every function name. Programmers remember that a tool exists, then look up how to spell it.

This page gives you:

  • one table per topic, in course order
  • a Run box wherever seeing beats reading
  • the traps worth keeping in your head

Simple lesson: remember that a tool exists, and look up the details here.

A Real-World Example

A developer writing a marks server forgets whether it is strings.Trim or strings.TrimSpace. They do not reread a whole tutorial. They open a reference, find the strings table, and get the answer in seconds. This page is that reference for everything in the course.

types and operators

if, switch, for

functions, packages

slices, maps, structs

interfaces, errors

files, goroutines

Go

Every topic of the course, on one page.

Here is most of the course working together in one program:

The whole course in one program

package main

import (
	"errors"
	"fmt"
	"sort"
)

type Result struct {
	Name    string
	Subject string
	Mark    int
}

func (r Result) Grade() string {
	if r.Mark >= 35 {
		return "pass"
	}
	return "fail"
}

var ErrEmpty = errors.New("no results")

func average(rs []Result) (float64, error) {
	if len(rs) == 0 {
		return 0, ErrEmpty
	}
	total := 0
	for _, r := range rs {
		total += r.Mark
	}
	return float64(total) / float64(len(rs)), nil
}

func main() {
	results := []Result{
		{"Asha", "Maths", 78},
		{"Ravi", "Science", 85},
		{"Meera", "English", 30},
	}
	sort.Slice(results, func(i, j int) bool { return results[i].Mark > results[j].Mark })

	count := map[string]int{}
	for _, r := range results {
		fmt.Printf("%-8s%-10s%4d  %s\n", r.Name, r.Subject, r.Mark, r.Grade())
		count[r.Grade()]++
	}

	avg, err := average(results)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%d of %d passed, average %.1f\n", count["pass"], len(results), avg)
}
Ravi    Science     85  pass
Asha    Maths       78  pass
Meera   English     30  fail
2 of 3 passed, average 64.3

Open this page at the section you need. Each heading matches a lesson you can go back to.

What You Will Learn

On this page, you will find:

  1. The syntax for every topic in the course.
  2. Run boxes for the trickiest parts.
  3. The traps worth remembering, in one table.

Data Types

Every basic type from the course, side by side:

TypeExampleZero valueNotes
int78064 bits on most computers
float6478.50Not exact: 0.1 + 0.2 != 0.3
string"Asha"""Cannot change. len counts bytes
booltruefalseNot a number: if 1 { } does not build
rune'अ'0One Unicode character (int32)
byte'A'0One byte (uint8)
[]int[]int{78, 85}nilSlice: grows with append
map[string]intmap[string]int{"Asha": 78}nilMake it before writing
*int&marknilAddress of a value

The ways to make a variable:

FormExampleWhere
Fullvar n int = 5Anywhere
Type from valuevar n = 5Anywhere
Shortn := 5Inside functions only
Manya, b := 1, 2Inside functions only
Constantconst Pass = 35Anywhere
Counting constantsconst ( A = iota; B; C )Anywhere
Ignore a value_, err := f()Anywhere

Keywords

Keyword = a word Go keeps for itself. You cannot use it as a name.

Go has only 25 keywords:

GroupKeywords
Programpackage import
Declarevar const type func
Typesstruct interface map chan
Decideif else switch case default fallthrough select
Repeatfor range break continue goto
Functionsreturn defer go

int, string, true, nil, len and append are not keywords. They are built-in names.

Operators

The operator groups:

GroupOperators
Arithmetic+ - * / %
Increase / decreasex++ x-- (statements, not values)
Comparison== != > < >= <=
Assignment= := += -= *= /= %=
Logical&& || !
Bitwise& | ^ &^ << >>
Address& (address of) * (value at)
Channel<-

Variables, types and operators

package main

import (
	"fmt"
	"strconv"
)

const passMark = 35

func main() {
	name := "Asha"
	marks, _ := strconv.Atoi("82")
	avg := float64(marks+90) / 2
	fmt.Println(name, marks >= passMark, avg, 17%5, 1<<3)
}
Asha true 86 2 8

Integer division drops the part after the point: 7 / 2 is 3. Convert first for 3.5: float64(7) / 2.

Conditional Statements

FormSyntaxNotes
if / elseif x > 0 { } else if x < 0 { } else { }No brackets around the condition
Short statementif v, err := f(); err == nil { }v lives only inside the if
switchswitch day { case "Sat", "Sun": ... default: ... }No break needed
No-value switchswitch { case m >= 90: ... }A cleaner if chain
fallthroughcase 1: ...; fallthroughRuns the next case too. Rarely used

{ must stay on the same line as if, else, for, switch and func. On the next line, Go will not build.

Loops

Go has one loop keyword, for, in four shapes:

ShapeSyntaxLike
Countingfor i := 0; i < n; i++ { }A normal for
Condition onlyfor x < 100 { }while in other languages
Foreverfor { ... break }while (true)
rangefor i, v := range list { }for each

What range gives you:

OverFirst valueSecond value
Slice or arrayindexelement (a copy)
Stringbyte indexrune
Mapkeyvalue (random order)
Channelvalue—
Number (Go 1.22+)0 to n-1—

Functions

TopicSyntaxNotes
Declarefunc add(a, b int) int { return a + b }Type after the name
Many resultsfunc div(a, b int) (int, error)The Go way to report errors
Named resultsfunc size() (w, h int)A bare return returns them
Variadicfunc sum(nums ...int) intCall with sum(list...)
Function valuef := func(x int) int { return x * k }A closure: remembers k
deferdefer f.Close()Runs when the function ends, last in first out

Conditions, loops and functions

package main

import "fmt"

func grade(m int) string {
	switch {
	case m >= 90:
		return "A"
	case m >= 75:
		return "B"
	default:
		return "C"
	}
}

func total(marks ...int) int {
	t := 0
	for _, m := range marks {
		t += m
	}
	return t
}

func main() {
	for _, m := range []int{95, 80, 60} {
		fmt.Print(grade(m), " ")
	}
	fmt.Println(total(10, 20, 30))
}
A B C 60

Packages and Modules

Command or ruleWhat it does
go mod init example.com/schoolStarts a module (makes go.mod)
go run .Builds and runs the program
go buildMakes one program file
go get github.com/google/uuidAdds a module
go mod tidyAdds what is used, removes what is not
Average vs totalCapital first letter = exported (other packages can use it)
import str "strings"Gives a package a short name
import _ "image/png"Runs a package's setup only

String Methods

The strings functions you will use most:

FunctionExampleResult
Containsstrings.Contains("Green Valley", "Val")true
HasPrefix / HasSuffixstrings.HasSuffix("a.txt", ".txt")true
Indexstrings.Index("Asha", "h")2
Split / Joinstrings.Split("a,b", ",")[a b]
ReplaceAllstrings.ReplaceAll("8-A", "-", "")"8A"
TrimSpacestrings.TrimSpace(" hi ")"hi"
ToUpper / ToLowerstrings.ToUpper("asha")"ASHA"
Repeatstrings.Repeat("-", 5)"-----"
Fieldsstrings.Fields(" a b ")[a b]

Also remember:

  • len(s) counts bytes. utf8.RuneCountInString(s) counts characters.
  • s[1:4] cuts bytes 1 to 3.
  • For many joins, use strings.Builder: b.WriteString("x"), then b.String().

String Formatting

The fmt verbs:

VerbPrintsExample output
%vAny value{Asha 78}
%+vStruct with field names{Name:Asha Mark:78}
%dWhole number78
%f / %.1fDecimal / one place64.3
%s / %qString / quoted string"Asha"
%ttrue or falsetrue
%TThe typeint
%-8s / %4dPad right / pad leftAsha / 78
%wWraps an error (fmt.Errorf only)—

Functions: Println (spaces and new line), Printf (verbs), Sprintf (returns the string), Errorf (returns an error).

Date and Time

TopicSyntaxNotes
Nowtime.Now()The current time
Make onetime.Date(2025, time.March, 14, 9, 30, 0, 0, time.UTC)Year, month, day, hour, min, sec, nsec, zone
Duration45 * time.MinuteAlso time.Second, time.Hour
Add / subtractt.Add(d), t2.Sub(t1)Sub gives a duration
Comparet1.Before(t2), t1.After(t2)
Formatt.Format("02/01/2006 15:04")Uses the reference date
Parsetime.Parse("2006-01-02", "2025-12-25")Same layout rules

Reference date = Mon Jan 2 15:04:05 2006. Remember it as 1 2 3 4 5 6: month 1, day 2, hour 3 (15), minute 4, second 5, year 6.

Strings and time

package main

import (
	"fmt"
	"strings"
	"time"
)

func main() {
	parts := strings.Split("Asha,8A,91", ",")
	fmt.Println(strings.ToUpper(parts[0]), len(parts))
	exam := time.Date(2025, time.March, 14, 9, 30, 0, 0, time.UTC)
	fmt.Println(exam.Add(3 * time.Hour).Format("02/01/2006 15:04"))
}
ASHA 3
14/03/2025 12:30

Collections

CollectionMakeAdd / changeNotes
Array[3]string{"a", "b", "c"}a[0] = "z"Fixed size. Copied when assigned
Slice[]int{1, 2}, make([]int, 0, 10)s = append(s, 3)Always store the result of append
Slice parts[1:3]—Shares the same array
Remove items = append(s[:i], s[i+1:]...)—Keeps the order
Copycopy(dst, src)—dst must have room
Mapmap[string]int{"a": 1}, make(map[string]int)m["b"] = 2Random order
Map lookupv, ok := m[k]delete(m, k)ok is false when missing

len(x) works on arrays, slices, maps, strings and channels. cap(s) tells how much room a slice has.

Pointers and Structs

TopicSyntaxNotes
Pointerp := &x, *p = 5& = address, * = value there
Structtype Student struct { Name string; Marks int }A group of fields
CreateStudent{Name: "Asha", Marks: 91}Missing fields get zero values
Value methodfunc (s Student) Grade() stringWorks on a copy
Pointer methodfunc (s *Student) Add(n int)Changes the real struct
Embedtype Teacher struct { Person; Subject string }Teacher gets Person's fields and methods
Hidemarks int + Marks() + SetMarks(m) errorSmall letter = private to the package
Custom typetype Celsius float64A new type with its own methods
Aliastype ID = intJust another name

Interfaces and Generics

TopicSyntaxNotes
Interfacetype Shape interface { Area() float64 }A list of methods
Satisfy itGive the type an Area() float64 methodNo implements word
Any valuevar x any = 5any = interface{}
Assertn, ok := x.(int)ok is false if it is not an int
Type switchswitch v := x.(type) { case int: ... }One case per type
Generic functionfunc Max[T int | float64](a, b T) TT is a type parameter
Constraintsany, comparable, interface{ ~int | ~float64 }What T may be
Sort recordssort.Slice(list, func(i, j int) bool { ... })Return true if i goes first

Structs, interfaces and generics

package main

import (
	"fmt"
	"sort"
)

type Shape interface{ Area() float64 }

type Rect struct{ W, H float64 }

func (r Rect) Area() float64 { return r.W * r.H }

type Square struct{ S float64 }

func (s Square) Area() float64 { return s.S * s.S }

func Largest[T int | float64](xs []T) T {
	best := xs[0]
	for _, x := range xs {
		if x > best {
			best = x
		}
	}
	return best
}

func main() {
	shapes := []Shape{Rect{2, 3}, Square{4}, Rect{1, 5}}
	sort.Slice(shapes, func(i, j int) bool { return shapes[i].Area() < shapes[j].Area() })
	var areas []float64
	for _, s := range shapes {
		areas = append(areas, s.Area())
	}
	fmt.Println(areas, Largest(areas))
}
[5 6 16] 16

Error Handling

TopicSyntaxNotes
Createerrors.New("msg")A simple error
Create with detailsfmt.Errorf("roll %d: %w", r, err)%w wraps the cause
Checkif err != nil { return err }Right after every call
Sentinelvar ErrNotFound = errors.New("not found")A named error to compare with
Is it this one?errors.Is(err, ErrNotFound)Looks through wrapped errors
Is it this type?errors.As(err, &myErr)Fills myErr if found
Panicpanic("bug")Stops the program. For bugs only
Recoverdefer func() { recover() }()Catches a panic inside defer

File Handling

TaskSyntaxNotes
Read alldata, err := os.ReadFile("a.txt")Gives []byte
Write allos.WriteFile("a.txt", data, 0644)Replaces the file
Openf, err := os.Open("a.txt") then defer f.Close()Read only
Linessc := bufio.NewScanner(f); for sc.Scan() { sc.Text() }One line at a time
Appendos.OpenFile(n, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)Adds to the end
Foldersos.MkdirAll(p, 0755), os.ReadDir(".")Make / list
Exists?_, err := os.Stat(n) then errors.Is(err, fs.ErrNotExist)

JSON

TaskSyntaxNotes
Go to JSONjson.Marshal(v)Gives []byte
Pretty JSONjson.MarshalIndent(v, "", " ")Two-space indent
JSON to Gojson.Unmarshal(data, &v)Pass a pointer
Rename a key`json:"name"`Field tag
Skip if empty`json:"name,omitempty"`
Never include`json:"-"`

Only exported (capital) fields go into JSON.

Errors, files and JSON

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"os"
)

type Config struct {
	School string `json:"school"`
	Year   int    `json:"year"`
}

func main() {
	_, err := os.ReadFile("missing.txt")
	fmt.Println(errors.Is(err, fs.ErrNotExist))

	data, _ := os.ReadFile("data/config.json")
	var c Config
	if err := json.Unmarshal(data, &c); err != nil {
		fmt.Println(err)
		return
	}
	out, _ := json.Marshal(c)
	fmt.Println(string(out))
}
true
{"school":"Green Valley School","year":2025}

Goroutines, Channels and Synchronization

The concurrency pieces and their jobs:

PieceSyntaxFor
Goroutinego work(), go func() { ... }()Run a job at the same time
WaitGroupwg.Add(1), defer wg.Done(), wg.Wait()Wait for jobs to finish
Channelch := make(chan int), make(chan int, 5)Pass values between goroutines
Send / receivech <- v, v := <-ch, v, ok := <-ch
End a streamclose(ch), for v := range ch { }Only the sender closes
selectselect { case v := <-a: ... case <-time.After(d): ... }Wait on many channels
Mutexmu.Lock(), defer mu.Unlock()One goroutine at a time
Atomicvar n atomic.Int64; n.Add(1)A safe counter
Race checkgo run -race main.goFinds unsafe sharing

Reflection and Context

TopicSyntaxNotes
Typereflect.TypeOf(x).Kind()int, struct, slice ...
Valuereflect.ValueOf(x)
Fieldst.NumField(), t.Field(i).Name, t.Field(i).Tag.Get("json")How JSON reads tags
Root contextcontext.Background()The start of every chain
Time limitctx, cancel := context.WithTimeout(parent, 2*time.Second)Always defer cancel()
Listencase <-ctx.Done(): return ctx.Err()Stop when told

Goroutines, channels and context

package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

func main() {
	results := make(chan int, 3)
	var wg sync.WaitGroup
	for i := 1; i <= 3; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results <- i * i
		}()
	}
	wg.Wait()
	close(results)
	sum := 0
	for r := range results {
		sum += r
	}
	fmt.Println("sum of squares:", sum)

	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	select {
	case <-time.After(time.Second):
		fmt.Println("finished")
	case <-ctx.Done():
		fmt.Println("stopped:", ctx.Err())
	}
}
sum of squares: 14
stopped: context deadline exceeded

Forgot a function? Ask Go. On your computer, go doc strings lists the strings package, and go doc strings.TrimSpace explains one function.

$ go doc strings.TrimSpace
func TrimSpace(s string) string
    TrimSpace returns a slice of the string s, with all leading and trailing
    white space removed, as defined by Unicode.

Easy Way to Remember:

  • Forgot a name? go doc it.
  • Got an error? Read the first line: file, line number, then the problem.
  • Not sure it is right? go vet it.

TL;DR

  1. Types = int, float64, string, bool, rune, slices, maps, structs, pointers.
  2. Control flow = if, switch, one for loop, range.
  3. Functions = many results, variadic, closures, defer.
  4. Types with behaviour = methods, embedding, interfaces, generics.
  5. Safety = errors as values, %w, errors.Is / errors.As.
  6. Files = os.ReadFile, os.WriteFile, encoding/json.
  7. Concurrency = go, WaitGroup, channels, select, Mutex, context.
  8. Lookup = go doc.

Common mistakes

The most common mistakes from the whole course, in one place.

MistakeWhat you seeWhy it happensFix
An unused variable or importdeclared and not usedGo refuses unused codeUse it, or remove it
{ on the next linesyntax error: unexpected newlineGo adds a ; at the line endKeep { on the same line
append(s, x) aloneThe new item is lostappend returns a new slices = append(s, x)
Writing to var m map[K]Vpanic: assignment to entry in nil mapThe map was never madem := make(map[K]V)
Changing the range valueNothing changesv is a copylist[i].Field = ...
7 / 2 expected to be 3.53Integer divisionfloat64(7) / 2
Ignoring errSilent wrong resultsErrors are plain valuesif err != nil { ... }
fmt.Errorf("...%v", err) to wraperrors.Is returns false%v turns it into textUse %w
main ends before goroutinesSome output is missingGo does not wait for themsync.WaitGroup
Two goroutines change one valueWrong totalsA data racesync.Mutex or a channel
No defer cancel()Timers stay aliveThe context is never releaseddefer cancel() right away
A lowercase field in JSONThe field is missingOnly exported fields are seenCapitalise it, add a tag

Check Yourself

Exercises

What to Remember

  • Nobody remembers everything. Know a tool exists, and look up the spelling.
  • go doc explains any package or function, with no internet.
  • Every variable and import must be used, and { stays on the same line.
  • Integer division drops the decimal part. Convert with float64() first.
  • Store the result of append. Make a map before you write to it.
  • range gives a copy. Change elements with list[i].
  • Errors are values. Check every err, and wrap with %w.
  • Capital first letter = exported: other packages and JSON can see it.
  • Wait for every goroutine. Lock shared data. defer cancel() every context.

You have finished the Go course. Keep practising: build a small project, like a library manager or a marks reporter, using what you learned.