Go Cheat Sheet
Quick reference from FreeCodingCourses.com
Variables and types
var x int = 5- explicit declaration.
y := 5- short form, type inferred. Only inside functions.
const pi = 3.14- a constant.
var s string var ok bool- zero values: "", false, 0.
var xs []int- a nil slice, ready to append to.
Functions
func add(a, b int) int { return a + b }- typed params and return.
func divide(a, b int) (int, error)- multiple returns; error is the Go convention.
q, err := divide(10, 2)- capture both values.
func sum(nums ...int) int- variadic: any number of ints.
defer file.Close()- run this when the function returns.
Slices and maps
xs := []int{1, 2, 3}- a slice (growable list).
xs = append(xs, 4)- append returns a new slice; reassign it.
len(xs) xs[1:3]- length and sub-slice.
m := map[string]int{"a": 1}- a map (key/value).
v, ok := m["a"]- ok is false if the key is missing.
Structs
type User struct { Name string Age int }- a struct groups fields.
u := User{Name: "Ada", Age: 36}- create one.
u.Name- access a field.
func (u User) Greet() string { ... }- a method on User.
Control flow
if x > 0 { ... } else { ... }- no parentheses, braces required.
for i := 0; i < 5; i++ { ... }- the only loop keyword in Go.
for i, v := range xs { ... }- range over a slice or map.
for cond { ... }- for with one condition acts like while.
switch x { case 1: ... default: ... }- no fallthrough by default.
Errors and goroutines
if err != nil { return err }- the error check you write constantly.
go doWork()- run a function concurrently in a goroutine.
ch := make(chan int)- a channel to pass values between goroutines.
ch <- 5 v := <-ch- send into and receive from a channel.
Unlock the full Go cheat sheet
You're seeing 2 of 6 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.