🐹 Go Language Cheatsheet

Quick reference for Go syntax, commands, and patterns

Variables & Types

Variable Declaration

var name string = "Gopher" var age int name := "Gopher" // Short declaration const PI = 3.14159

Basic Types

bool, string int, int8, int16, int32, int64 uint, uint8, uint16, uint32, uint64 float32, float64 complex64, complex128 byte (alias for uint8) rune (alias for int32)

Type Conversion

i := 42 f := float64(i) u := uint(f)

Control Flow

If Statement

if x < 0 { return negative } else if x == 0 { return zero } else { return positive } // With initialization if v := getValue(); v < limit { return v }

For Loop

// Traditional for i := 0; i < 10; i++ { } // While-like for x < y { } // Infinite for { } // Range for i, v := range slice { fmt.Printf("%d: %v\n", i, v) }

Switch

switch os := runtime.GOOS; os { case "darwin": fmt.Println("macOS") case "linux": fmt.Println("Linux") default: fmt.Printf("%s", os) }

Functions

Function Declaration

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 }

Variadic Functions

func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total }

Closures

func adder() func(int) int { sum := 0 return func(x int) int { sum += x return sum } }

Data Structures

Arrays & Slices

// Array var a [5]int b := [3]int{1, 2, 3} // Slice var s []int s = make([]int, 5, 10) // len=5, cap=10 s = append(s, 1, 2, 3) // Slice from array slice := b[0:2]

Maps

m := make(map[string]int) m["key"] = 42 // Map literal m = map[string]int{ "apple": 5, "banana": 3, } // Check existence v, ok := m["key"] if ok { fmt.Println(v) } // Delete delete(m, "key")

Structs

type Person struct { Name string Age int } p := Person{Name: "Alice", Age: 30} p.Age = 31 // Anonymous struct pet := struct { name string kind string }{ name: "Fluffy", kind: "cat", }

Interfaces & Methods

Methods

type Vertex struct { X, Y float64 } // Value receiver func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } // Pointer receiver func (v *Vertex) Scale(f float64) { v.X *= f v.Y *= f }

Interfaces

type Writer interface { Write([]byte) (int, error) } type MyWriter struct{} func (w MyWriter) Write(data []byte) (int, error) { return len(data), nil } // Empty interface var i interface{} i = 42 i = "hello"

Type Assertions

var i interface{} = "hello" s := i.(string) // Panic if wrong type s, ok := i.(string) // Safe assertion // Type switch switch v := i.(type) { case int: fmt.Printf("Integer: %d", v) case string: fmt.Printf("String: %s", v) }

Concurrency

Goroutines

go func() { fmt.Println("Running concurrently") }() // With parameters go processItem(item)

Channels

// Create channel ch := make(chan int) ch := make(chan int, 100) // Buffered // Send and receive ch <- 42 // Send v := <-ch // Receive v, ok := <-ch // Receive with check // Close channel close(ch) // Range over channel for v := range ch { fmt.Println(v) }

Select

select { case msg1 := <-ch1: fmt.Println("Received", msg1) case msg2 := <-ch2: fmt.Println("Received", msg2) case <-timeout: fmt.Println("Timeout") default: fmt.Println("No message") }

Error Handling

Error Interface

type error interface { Error() string } // Creating errors err := errors.New("something went wrong") err := fmt.Errorf("error: %v", details)

Error Handling Pattern

result, err := doSomething() if err != nil { return fmt.Errorf("failed: %w", err) } // Multiple error checks if err := step1(); err != nil { return err } if err := step2(); err != nil { return err }

Defer, Panic, Recover

// Defer - cleanup defer file.Close() // Panic panic("something bad happened") // Recover defer func() { if r := recover(); r != nil { fmt.Println("Recovered:", r) } }()

Go Commands

Command Description
go run main.go Run a Go program
go build Compile the program
go test Run tests
go mod init Initialize module
go mod tidy Clean up dependencies
go get pkg Download dependencies
go fmt Format code
go vet Examine code
go doc Show documentation

Common Patterns

Worker Pool

jobs := make(chan int, 100) results := make(chan int, 100) // Start workers for w := 1; w <= 3; w++ { go worker(w, jobs, results) } // Send jobs for j := 1; j <= 5; j++ { jobs <- j } close(jobs) // Collect results for a := 1; a <= 5; a++ { <-results }

Singleton

var instance *Singleton var once sync.Once func GetInstance() *Singleton { once.Do(func() { instance = &Singleton{} }) return instance }

Options Pattern

type Option func(*Server) func WithPort(port int) Option { return func(s *Server) { s.port = port } } func NewServer(opts ...Option) *Server { s := &Server{port: 8080} for _, opt := range opts { opt(s) } return s }