Go
Go (Golang) cheat sheet covering syntax, goroutines, channels, interfaces, error handling, and concurrency patterns with examples.
Sign in to mark items as known and track your progress.
Sign inSetup & Basics
Getting started with Go
Installation & Setup
Installing Go and setting up development environment
# Download and install Go
# Visit https://go.dev/dl/ for latest version
# Verify installation
go version
# Initialize a new module
go mod init example.com/myapp
# Run a Go program
go run main.goBasic Syntax
Go program structure and syntax
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
// Variables
var name string = "Go"
age := 25 // Short declarationData Types & Structures
Go data types, arrays, slices, maps, and structs
Arrays & Slices
Working with arrays and slices
// Arrays (fixed size)
var arr [5]int
arr[0] = 10
// Slices (dynamic)
slice := []int{1, 2, 3}
slice = append(slice, 4)
// Make slice
s := make([]int, 5, 10) // len=5, cap=10Maps
Working with maps (hash tables)
// Create map
m := make(map[string]int)
m["key"] = 42
// Map literal
ages := map[string]int{
"Alice": 25,
"Bob": 30,
}
// Check if key exists
val, ok := ages["Alice"]Structs
Defining and using structs
// Define struct
type Person struct {
Name string
Age int
}
// Create instance
p := Person{Name: "Alice", Age: 25}
p.Age = 26 // Access fieldStruct Embedding
Composition via embedding structs and interfaces
// Embed struct for composition
type Address struct {
City string
Country string
}
type Person struct {
Name string
Address // Embedded (promoted fields)
}
p := Person{
Name: "Alice",
Address: Address{City: "NYC", Country: "US"},
}
fmt.Println(p.City) // "NYC" (promoted)Pointers
Working with pointers and memory addresses
Pointers
Pointer basics, dereferencing, and nil pointers
// Declare a pointer
var p *int
// Get address of variable
x := 42
p = &x
// Dereference (access value)
fmt.Println(*p) // 42
// Modify via pointer
*p = 100
fmt.Println(x) // 100
// Nil pointer check
if p != nil {
fmt.Println(*p)
}Control Flow
Conditionals, loops, and control structures
Conditionals
If statements and switch cases
// If statement
if x > 0 {
fmt.Println("Positive")
} else if x < 0 {
fmt.Println("Negative")
} else {
fmt.Println("Zero")
}
// Switch
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
default:
fmt.Println("Other")
}Loops
For loops and iterations
// Basic for loop
for i := 0; i < 10; i++ {
fmt.Println(i)
}
// While-style loop
for x < 100 {
x *= 2
}
// Range over slice
for i, v := range slice {
fmt.Printf("%d: %v\n", i, v)
}Functions
Functions, methods, and closures
Functions
Function declaration and usage
// Basic function
func add(x, y int) int {
return x + y
}
// Multiple returns
func swap(x, y string) (string, string) {
return y, x
}
// Named returns
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // Naked return
}Methods
Methods on types and interfaces
type Rectangle struct {
Width, Height float64
}
// Value receiver
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Pointer receiver
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}Closures
Anonymous functions and closures
// Anonymous function
greet := func(name string) string {
return "Hello, " + name
}
fmt.Println(greet("Go"))
// Closure captures variables
counter := func() func() int {
n := 0
return func() int {
n++
return n
}
}()
fmt.Println(counter()) // 1
fmt.Println(counter()) // 2Interfaces
Interface types and polymorphism
Interfaces
Defining and implementing interfaces
// Define interface
type Shape interface {
Area() float64
Perimeter() float64
}
// Implement interface
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}Type Assertions & Switches
Extract concrete types from interfaces
// Type assertion
var i interface{} = "hello"
s := i.(string) // Panics if wrong type
s, ok := i.(string) // Safe: ok = false if wrong
// Type switch
switch v := i.(type) {
case string:
fmt.Println("string:", v)
case int:
fmt.Println("int:", v)
default:
fmt.Println("unknown")
}Generics
Type parameters and constraints
Generics
Generic functions and types with type parameters
// Generic function
func Map[T any, U any](s []T, f func(T) U) []U {
result := make([]U, len(s))
for i, v := range s {
result[i] = f(v)
}
return result
}
// Constrained generic
func Min[T int | float64 | string](a, b T) T {
if a < b { return a }
return b
}Concurrency
Goroutines, channels, and synchronization
Goroutines
Concurrent execution with goroutines
// Start goroutine
go doSomething()
// Anonymous goroutine
go func() {
fmt.Println("Hello from goroutine")
}()
// Wait for completion
time.Sleep(time.Second)Channels
Communication between goroutines
// Create channel
ch := make(chan int)
// Send to channel
ch <- 42
// Receive from channel
value := <-ch
// Buffered channel
ch := make(chan int, 100)Select Statement
Multiplex channel operations with select
// Select waits on multiple channels
select {
case msg := <-ch1:
fmt.Println("From ch1:", msg)
case msg := <-ch2:
fmt.Println("From ch2:", msg)
case ch3 <- "hello":
fmt.Println("Sent to ch3")
default:
fmt.Println("No channel ready")
}Sync Primitives
Mutex, WaitGroup, and Once for synchronization
// WaitGroup: wait for goroutines
var wg sync.WaitGroup
for i := range 5 {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println(i)
}()
}
wg.Wait()
// Mutex: protect shared state
var mu sync.Mutex
mu.Lock()
// critical section
mu.Unlock()Error Handling
Error handling patterns and best practices
Error Handling
Working with errors in Go
// Return error
func divide(x, y float64) (float64, error) {
if y == 0 {
return 0, errors.New("division by zero")
}
return x / y, nil
}
// Check error
result, err := divide(10, 0)
if err != nil {
log.Fatal(err)
}Defer, Panic & Recover
Deferred execution, panics, and recovery
// Defer: runs when function returns (LIFO)
f, _ := os.Open("file.txt")
defer f.Close() // Guaranteed cleanup
// Panic: unrecoverable error
panic("something went wrong")
// Recover: catch panics
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()String Formatting
fmt package verbs and string operations
fmt Verbs & Formatting
Printf verbs and string formatting functions
// Common verbs
fmt.Printf("%v", val) // Default format
fmt.Printf("%+v", s) // Struct with field names
fmt.Printf("%#v", s) // Go-syntax representation
fmt.Printf("%T", val) // Type of value
fmt.Printf("%d", 42) // Integer
fmt.Printf("%s", "hi") // String
fmt.Printf("%f", 3.14) // Float
fmt.Printf("%t", true) // Boolean
fmt.Printf("%p", &val) // Pointer
// Sprintf returns string
msg := fmt.Sprintf("Hello, %s!", name)Context
Cancellation, timeouts, and request-scoped values
Context
Cancellation, timeouts, and passing request-scoped data
// With cancel
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// With timeout
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Check if done
select {
case <-ctx.Done():
fmt.Println(ctx.Err()) // context canceled
}JSON
Encoding and decoding JSON data
JSON Encoding & Decoding
Marshal, Unmarshal, and struct tags for JSON
// Struct with JSON tags
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Age int `json:"age"`
}
// Encode (struct → JSON)
data, _ := json.Marshal(user)
// Decode (JSON → struct)
var u User
json.Unmarshal(data, &u)HTTP Server & Client
Building HTTP servers and making requests
HTTP Server & Client
net/http server handlers and HTTP client requests
// Simple server
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
// GET request
resp, _ := http.Get("https://api.example.com/data")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)Testing
Writing and running tests
Testing
Unit tests and benchmarks
// math_test.go
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
// Run tests
// go test
// go test -v
// go test -coverPackages & Modules
Package management and module system
Packages & Imports
Organizing code with packages
// Package declaration
package main
// Imports
import (
"fmt"
"math/rand"
"github.com/user/package"
)
// Package alias
import m "math"