๐Ÿน

Go Cheat Sheet

Built at Google for fast, simple, reliable cloud software โ€” Go compiles to a single native binary, has built-in concurrency, and is the language behind Docker, Kubernetes, and huge chunks of modern cloud infrastructure. Copy-paste examples plus live Run/Submit exercises.

Jump to: Your first programVariablesif / else LoopsSlicesMaps FunctionsStructsGoroutines ๐Ÿš€ Practice problems

Your first program

package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}
๐Ÿ“ Every Go file starts with a package declaration. Run programs with go run file.go, or build a real executable with go build.

Variables

var age int = 25
name := "Sam"          // := infers the type automatically โ€” the idiomatic way
const Pi = 3.14159     // constants can't change

if / else

age := 20
if age >= 18 {
    fmt.Println("Adult")
} else if age >= 13 {
    fmt.Println("Teen")
} else {
    fmt.Println("Child")
}
๐Ÿ“ Go has no parentheses around the condition, and no ternary operator โ€” this is deliberate; Go's whole philosophy is "one obvious way to do it."

Loops

Go has exactly one loop keyword โ€” for โ€” used for everything.

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

n := 3
for n > 0 {   // this IS Go's "while" loop
    fmt.Println(n)
    n--
}

Slices

Go's resizable array โ€” what you use almost everywhere instead of a fixed-size array.

nums := []int{10, 20, 30}
nums = append(nums, 40)     // append returns a NEW slice โ€” always reassign it
fmt.Println(nums[0])       // 10
fmt.Println(len(nums))      // 4

for _, n := range nums {  // range gives (index, value); _ discards the index
    fmt.Println(n)
}

Maps

ages := map[string]int{"Sam": 25, "Ana": 30}
fmt.Println(ages["Sam"])   // 25
ages["Lee"] = 40       // add a new key

value, exists := ages["Zed"]   // the "comma ok" idiom โ€” check if a key exists
fmt.Println(exists)      // false

Functions

func add(a int, b int) int {
    return a + b
}

// Go functions can return MULTIPLE values โ€” used constantly for error handling
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

Structs

type Dog struct {
    Name string
    Age  int
}

func (d Dog) Bark() {     // a "method" โ€” a function attached to a type
    fmt.Println(d.Name + " says woof!")
}

// d := Dog{Name: "Rex", Age: 3}; d.Bark()

Goroutines

Go's built-in concurrency โ€” running functions at the same time is a language feature, not a library bolted on afterward.

go doSomething()   // runs doSomething() concurrently, without blocking

// channels let goroutines safely send data to each other
ch := make(chan int)
go func() { ch <- 42 }()
result := <-ch   // blocks until a value arrives

๐Ÿš€ Practice problems

Full runnable programs, compiled and run in a real Go sandbox โ€” same workspace as the other cheat sheets.

Sum a slice EASY

package main

import "fmt"

func main() {
    nums := []int{4, 8, 15, 16, 23, 42}
    sum := 0
    for _, n := range nums {
        sum += n
    }
    fmt.Println(sum)
}

Reverse a string MEDIUM

package main

import "fmt"

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func main() {
    fmt.Println(reverse("golang"))
}

Struct with a method MEDIUM

package main

import "fmt"

type Rectangle struct {
    Width, Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func main() {
    r := Rectangle{Width: 4, Height: 5}
    fmt.Println(r.Area())
}

Word frequency with a map HARD

package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "the cat sat on the mat the cat ran"
    counts := map[string]int{}
    for _, word := range strings.Fields(text) {
        counts[word]++
    }
    for word, n := range counts {
        fmt.Printf("%s: %d\n", word, n)
    }
}