Skip to content

Quick Reference

A concise reference for common Go patterns and syntax.

// Variable declaration
var name string = "Go"
var age int // Zero value: 0
count := 10 // Short declaration (type inferred)
// Constants
const Pi = 3.14159
const (
StatusOK = 200
StatusError = 500
)
// 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 (Unicode code point)
// 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=5
slice := make([]int, 0, 10) // len=0, cap=10
slice = append(slice, 4, 5)
// Maps
m := map[string]int{"a": 1, "b": 2}
m := make(map[string]int)
m["key"] = value
value, exists := m["key"]
delete(m, "key")
// Structs
type Person struct {
Name string
Age int
}
p := Person{Name: "Alice", Age: 30}
p := Person{"Alice", 30} // Positional
// If statement
if x > 0 {
// ...
} else if x < 0 {
// ...
} else {
// ...
}
// If with initialization
if err := doSomething(); err != nil {
return err
}
// Switch
switch day {
case "Mon", "Tue":
// Multiple values
case "Wed":
// ...
default:
// ...
}
// Type switch
switch 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 loop
for { } // Infinite loop
for i, v := range slice { } // Range over slice
for k, v := range m { } // Range over map
// Basic function
func add(a, b int) int {
return a + b
}
// Multiple returns
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named returns
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // Naked return
}
// Variadic function
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Function as value
fn := func(x int) int { return x * 2 }
// Closures
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Defer (LIFO order)
defer file.Close()
defer func() { recover() }()
// Method with value receiver
func (p Person) Greet() string {
return "Hello, " + p.Name
}
// Method with pointer receiver
func (p *Person) SetAge(age int) {
p.Age = age
}
// Interface
type Reader interface {
Read(p []byte) (n int, err error)
}
// Interface composition
type ReadWriter interface {
Reader
Writer
}
// Empty interface (any type)
var x interface{} // or: var x any
// Type assertion
s := x.(string) // Panics if wrong type
s, ok := x.(string) // Safe assertion
// Return error
func doSomething() error {
if problem {
return errors.New("something went wrong")
}
return nil
}
// Custom error
type 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 checking
if errors.Is(err, os.ErrNotExist) { }
var myErr *MyError
if errors.As(err, &myErr) { }
// Goroutine
go doSomething()
go func() { /* ... */ }()
// Channel
ch := make(chan int) // Unbuffered
ch := make(chan int, 10) // Buffered
ch <- value // Send
value := <-ch // Receive
close(ch) // Close
// Select
select {
case v := <-ch1:
// Received from ch1
case ch2 <- x:
// Sent to ch2
case <-time.After(time.Second):
// Timeout
default:
// Non-blocking
}
// WaitGroup
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// Work
}()
wg.Wait()
// Mutex
var mu sync.Mutex
mu.Lock()
// Critical section
mu.Unlock()
// Once
var once sync.Once
once.Do(func() {
// Run only once
})
// Create contexts
ctx := context.Background()
ctx := context.TODO()
// With cancellation
ctx, cancel := context.WithCancel(parent)
defer cancel()
// With timeout
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
// With deadline
ctx, cancel := context.WithDeadline(parent, time.Now().Add(time.Hour))
defer cancel()
// With value
ctx = context.WithValue(ctx, key, value)
value := ctx.Value(key)
// Check done
select {
case <-ctx.Done():
return ctx.Err()
default:
// Continue
}
// Generic function
func Min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
// Generic type
type Stack[T any] struct {
items []T
}
// Constraints
type Number interface {
int | int64 | float64
}
// Type approximation
type Integer interface {
~int | ~int64 // Matches underlying type
}
// Built-in constraints
any // Any type
comparable // Types supporting == and !=
// Map lookup
value, ok := m[key]
if !ok {
// Key not found
}
// Type assertion
s, ok := x.(string)
if !ok {
// Not a string
}
// Channel receive
value, ok := <-ch
if !ok {
// Channel closed
}
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
}
// Usage
server := NewServer(WithPort(9000))
func NewPerson(name string) *Person {
return &Person{
Name: name,
CreatedAt: time.Now(),
}
}
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
}
// Usage
query := new(QueryBuilder).Table("users").Where("active = true")
// Basic test
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
// Table-driven test
func 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)
}
})
}
}
// Benchmark
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}
Terminal window
# Build & Run
go run main.go
go build -o app
go install
# Testing
go test ./...
go test -v -run TestName
go test -bench=.
go test -cover
# Dependencies
go mod init module-name
go mod tidy
go get package@version
# Tools
go fmt ./...
go vet ./...
go doc fmt.Println
# Environment
go env
go version
TypeZero Value
boolfalse
int, float640
string""
pointer, slice, map, chan, func, interfacenil
structAll fields zero
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
)