Quick Reference
Go Quick Reference
Section titled “Go Quick Reference”A concise reference for common Go patterns and syntax.
Variables & Types
Section titled “Variables & Types”// Variable declarationvar name string = "Go"var age int // Zero value: 0count := 10 // Short declaration (type inferred)
// Constantsconst Pi = 3.14159const ( StatusOK = 200 StatusError = 500)
// Basic typesbool, stringint, int8, int16, int32, int64uint, uint8, uint16, uint32, uint64float32, float64complex64, complex128byte // alias for uint8rune // alias for int32 (Unicode code point)Composite Types
Section titled “Composite Types”// Arrays (fixed size)var arr [3]int = [3]int{1, 2, 3}arr := [...]int{1, 2, 3} // Size inferred
// Slices (dynamic)slice := []int{1, 2, 3}slice := make([]int, 5) // len=5, cap=5slice := make([]int, 0, 10) // len=0, cap=10slice = append(slice, 4, 5)
// Mapsm := map[string]int{"a": 1, "b": 2}m := make(map[string]int)m["key"] = valuevalue, exists := m["key"]delete(m, "key")
// Structstype Person struct { Name string Age int}p := Person{Name: "Alice", Age: 30}p := Person{"Alice", 30} // PositionalControl Flow
Section titled “Control Flow”// If statementif x > 0 { // ...} else if x < 0 { // ...} else { // ...}
// If with initializationif err := doSomething(); err != nil { return err}
// Switchswitch day {case "Mon", "Tue": // Multiple valuescase "Wed": // ...default: // ...}
// Type switchswitch v := x.(type) {case int: fmt.Println("int:", v)case string: fmt.Println("string:", v)}
// For loop (only loop in Go)for i := 0; i < 10; i++ { }for condition { } // While loopfor { } // Infinite loopfor i, v := range slice { } // Range over slicefor k, v := range m { } // Range over mapFunctions
Section titled “Functions”// Basic functionfunc add(a, b int) int { return a + b}
// Multiple returnsfunc divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil}
// Named returnsfunc split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return // Naked return}
// Variadic functionfunc sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total}
// Function as valuefn := func(x int) int { return x * 2 }
// Closuresfunc counter() func() int { count := 0 return func() int { count++ return count }}
// Defer (LIFO order)defer file.Close()defer func() { recover() }()Methods & Interfaces
Section titled “Methods & Interfaces”// Method with value receiverfunc (p Person) Greet() string { return "Hello, " + p.Name}
// Method with pointer receiverfunc (p *Person) SetAge(age int) { p.Age = age}
// Interfacetype Reader interface { Read(p []byte) (n int, err error)}
// Interface compositiontype ReadWriter interface { Reader Writer}
// Empty interface (any type)var x interface{} // or: var x any
// Type assertions := x.(string) // Panics if wrong types, ok := x.(string) // Safe assertionError Handling
Section titled “Error Handling”// Return errorfunc doSomething() error { if problem { return errors.New("something went wrong") } return nil}
// Custom errortype MyError struct { Code int Message string}
func (e *MyError) Error() string { return fmt.Sprintf("error %d: %s", e.Code, e.Message)}
// Error wrapping (Go 1.13+)err := fmt.Errorf("failed to process: %w", originalErr)
// Error checkingif errors.Is(err, os.ErrNotExist) { }var myErr *MyErrorif errors.As(err, &myErr) { }Concurrency
Section titled “Concurrency”// Goroutinego doSomething()go func() { /* ... */ }()
// Channelch := make(chan int) // Unbufferedch := make(chan int, 10) // Bufferedch <- value // Sendvalue := <-ch // Receiveclose(ch) // Close
// Selectselect {case v := <-ch1: // Received from ch1case ch2 <- x: // Sent to ch2case <-time.After(time.Second): // Timeoutdefault: // Non-blocking}
// WaitGroupvar wg sync.WaitGroupwg.Add(1)go func() { defer wg.Done() // Work}()wg.Wait()
// Mutexvar mu sync.Mutexmu.Lock()// Critical sectionmu.Unlock()
// Oncevar once sync.Onceonce.Do(func() { // Run only once})Context
Section titled “Context”// Create contextsctx := context.Background()ctx := context.TODO()
// With cancellationctx, cancel := context.WithCancel(parent)defer cancel()
// With timeoutctx, cancel := context.WithTimeout(parent, 5*time.Second)defer cancel()
// With deadlinectx, cancel := context.WithDeadline(parent, time.Now().Add(time.Hour))defer cancel()
// With valuectx = context.WithValue(ctx, key, value)value := ctx.Value(key)
// Check doneselect {case <-ctx.Done(): return ctx.Err()default: // Continue}Generics (Go 1.18+)
Section titled “Generics (Go 1.18+)”// Generic functionfunc Min[T constraints.Ordered](a, b T) T { if a < b { return a } return b}
// Generic typetype Stack[T any] struct { items []T}
// Constraintstype Number interface { int | int64 | float64}
// Type approximationtype Integer interface { ~int | ~int64 // Matches underlying type}
// Built-in constraintsany // Any typecomparable // Types supporting == and !=Common Patterns
Section titled “Common Patterns”Comma-OK Idiom
Section titled “Comma-OK Idiom”// Map lookupvalue, ok := m[key]if !ok { // Key not found}
// Type assertions, ok := x.(string)if !ok { // Not a string}
// Channel receivevalue, ok := <-chif !ok { // Channel closed}Functional Options
Section titled “Functional Options”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}
// Usageserver := NewServer(WithPort(9000))Constructor Pattern
Section titled “Constructor Pattern”func NewPerson(name string) *Person { return &Person{ Name: name, CreatedAt: time.Now(), }}Builder Pattern
Section titled “Builder Pattern”type QueryBuilder struct { table string where []string limit int}
func (b *QueryBuilder) Table(name string) *QueryBuilder { b.table = name return b}
func (b *QueryBuilder) Where(cond string) *QueryBuilder { b.where = append(b.where, cond) return b}
// Usagequery := new(QueryBuilder).Table("users").Where("active = true")Testing
Section titled “Testing”// Basic testfunc TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("Add(2, 3) = %d; want 5", result) }}
// Table-driven testfunc TestAdd(t *testing.T) { tests := []struct { name string a, b int expected int }{ {"positive", 2, 3, 5}, {"negative", -1, -1, -2}, {"zero", 0, 0, 0}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Add(tt.a, tt.b); got != tt.expected { t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.expected) } }) }}
// Benchmarkfunc BenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { Add(1, 2) }}Common Commands
Section titled “Common Commands”# Build & Rungo run main.gogo build -o appgo install
# Testinggo test ./...go test -v -run TestNamego test -bench=.go test -cover
# Dependenciesgo mod init module-namego mod tidygo get package@version
# Toolsgo fmt ./...go vet ./...go doc fmt.Println
# Environmentgo envgo versionZero Values
Section titled “Zero Values”| Type | Zero Value |
|---|---|
bool | false |
int, float64 | 0 |
string | "" |
pointer, slice, map, chan, func, interface | nil |
struct | All fields zero |
Common Imports
Section titled “Common Imports”import ( "context" // Cancellation and deadlines "encoding/json"// JSON encoding/decoding "errors" // Error handling "fmt" // Formatting I/O "io" // I/O primitives "log" // Logging "net/http" // HTTP client/server "os" // OS functionality "path/filepath"// File paths "sort" // Sorting "strconv" // String conversions "strings" // String manipulation "sync" // Synchronization "time" // Time and duration)