Skip to content

Instantly share code, notes, and snippets.

@amir-saniyan
Created May 18, 2026 11:10
Show Gist options
  • Select an option

  • Save amir-saniyan/7d50f374a5081da72c64b88e031b0ae0 to your computer and use it in GitHub Desktop.

Select an option

Save amir-saniyan/7d50f374a5081da72c64b88e031b0ae0 to your computer and use it in GitHub Desktop.
Go Cheat Sheet

Go Cheat Sheet

Table of Contents


Go Syntax

1. Basic Syntax

package main

func main() {
    // statements
}
  • Semicolons are automatically inserted at line endings; you rarely write them explicitly.
  • Case of first letter determines visibility: uppercase → exported, lowercase → unexported.

2. Comments

// single-line comment

/*
   multi-line comment
*/

3. Declarations & Identifiers

var name type          // declaration
var name type = value  // declaration with initialization
var x, y int = 1, 2    // multiple
var z = 42             // type inferred
z := 42                // short declaration (only inside functions)

// Short declaration must declare at least one new variable in the current scope
x, err := foo()        // ok if err is new; x is reassigned if already declared

4. Types & Type Conversions

Basic types:

bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte    // alias for uint8
rune    // alias for int32 (Unicode code point)

float32 float64
complex64 complex128

Type conversion:

var i int = 42
var f float64 = float64(i)

var u uint = uint(f)

Underlying type declarations:

type MyInt int   // MyInt is a distinct type, not an alias

5. Constants & iota

const Pi = 3.14
const (
    StatusOK = 200
    StatusNotFound = 404
)

// iota increments in a const block, reset for each new const keyword
const (
    A = iota       // 0
    B              // 1 (implicitly = iota)
    C              // 2
)

// Skip values, use expressions
const (
    _ = iota             // 0, skipped
    KB = 1 << (10 * iota) // 1 << (10*1) = 1024
    MB                    // 1 << (10*2) = 1048576
)

6. Control Flow

if/else

if x > 0 {
    // ...
} else if x == 0 {
    // ...
} else {
    // ...
}

// Statement before condition; scope of variable limited to if/else blocks
if v := someFunc(); v < 10 {
    return v
} else {
    return -v
}

for loops

The only loop construct is for.

// Classic C-style
for i := 0; i < 10; i++ {
    // ...
}

// Condition only (while loop)
for i < 10 {
    // ...
}

// Infinite loop
for {
    // ...
    break
}

// Range loop over arrays, slices, maps, strings, channels
for index, value := range collection {
    // use index and value
}

// Ignore index or value
for _, value := range collection { }
for index := range collection { }

switch

switch expression {
case value1:
    // ...
case value2:
    // ...
default:
    // ...
}

// Cases break automatically; use fallthrough to continue to next case
switch x {
case 1:
    // ...
    fallthrough
case 2:
    // ...
}

// Switch without expression (true is implicit)
switch {
case x < 0:
    // ...
case x == 0:
    // ...
default:
    // ...
}

// Type switch (used with interfaces)
switch v := x.(type) {
case int:
    // v is int
case string:
    // v is string
default:
    // ...
}

7. Functions

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

// Parameter type shorthand: a, b both int
func add(a, b int) int {
    return a + b
}

// Multiple return values
func swap(a, b string) (string, string) {
    return b, a
}

// Named return values: parameters act as local variables, bare return works
func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

// Variadic functions (variable number of arguments)
func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}
nums := []int{1, 2, 3}
s := sum(nums...) // spread slice into variadic

// Functions are values; can be assigned, passed, returned
var f func(int) int
f = func(x int) int { return x * 2 }

// Closures: inner function references outer variables
func outer() func() int {
    count := 0
    return func() int {
        count++  // mutates outer variable
        return count
    }
}

8. Defer, Panic, and Recover

// defer schedules a function call to run after the surrounding function returns.
func readFile() error {
    f, err := os.Open("file.txt")
    if err != nil {
        return err
    }
    defer f.Close()
    // ... use f
}

// Deferred calls execute in LIFO order; arguments are evaluated immediately.

// panic stops normal execution, runs deferred functions, then crashes.
if somethingBad {
    panic("unexpected condition")
}

// recover regains control inside a deferred function; returns nil if no panic.
func safeCall() (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered from panic: %v", r)
        }
    }()
    mayPanic()
    return nil
}

9. Structs & Methods

// Define struct type
type Person struct {
    Name string
    Age  int
}

// Create struct values
p1 := Person{"Alice", 30}
p2 := Person{Name: "Bob"}   // Age zero-value (0)
p3 := Person{}              // all zero values

// Access fields
p1.Name = "Eve"

// Methods: function with a receiver (value or pointer)
func (p Person) Greet() string {
    return "Hello, " + p.Name
}

// Pointer receiver to modify the struct
func (p *Person) Birthday() {
    p.Age++
}

// Call methods
p1.Greet()
p1.Birthday()  // Go automatically takes address for pointer receiver

// Embedding (composition, not inheritance)
type Employee struct {
    Person      // embedded field (anonymous)
    Company string
}

e := Employee{Person{"Charlie", 25}, "ACME"}
e.Name        // promoted from Person
e.Greet()     // method promoted

10. Pointers

var p *int          // nil pointer
i := 42
p = &i             // point to i
*p = 21            // modify i through pointer

// The new function returns a pointer to a zero value of the type
ptr := new(int)    // *int, pointing to 0
*ptr = 10

// No pointer arithmetic

11. Interfaces

// Interface defines behavior
type Shape interface {
    Area() float64
    Perimeter() float64
}

// Types implicitly satisfy an interface
type Rectangle struct { Width, Height float64 }

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

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

// A function can accept any Shape
func PrintArea(s Shape) {
    fmt.Println(s.Area())
}

var s Shape
s = Rectangle{3, 4}
PrintArea(s)

// The empty interface{} holds any type (now prefer any, alias for interface{})
var v interface{}
v = 42
v = "hello"

// Type assertion
str, ok := v.(string)  // safe: ok true if string, else false
num := v.(int)          // panics if not int

12. Arrays & Slices

Arrays (fixed size)

var a [5]int               // [0 0 0 0 0]
b := [3]string{"a", "b", "c"}
c := [...]int{1, 2, 3}     // size inferred
// Arrays are values; assigning copies the whole array

Slices (dynamic size)

// Create slices
var s []int                       // nil slice, len=0
s = []int{1, 2, 3}               // literal
s = make([]int, 3)               // len=3, cap=3, elements zeroed
s = make([]int, 3, 5)            // len=3, cap=5

// Slicing an array or slice
arr := [5]int{1,2,3,4,5}
s1 := arr[1:4]   // elements 2,3,4 (index 1 to 3)
s2 := arr[:3]    // 1,2,3
s3 := arr[2:]    // 3,4,5

// Append to a slice
s = append(s, 4)          // single element
s = append(s, 5, 6, 7)    // multiple
s1 = append(s1, s2...)    // merge two slices

// Length and capacity
len(s)   // number of elements
cap(s)   // capacity

// Copy elements
copy(dst, src) // copies min(len(dst), len(src)) elements

13. Maps

// Create maps
var m map[string]int      // nil map (reading is ok, writing panics)
m = make(map[string]int)  // empty, ready to use
m = map[string]int{
    "key1": 42,
    "key2": 13,
}

// Access and modify
m["foo"] = 100
value := m["bar"]         // zero value if key not present
value, ok := m["bar"]     // ok is true if key exists
delete(m, "key1")

// Iteration order is not specified
for key, val := range m {
    // ...
}

14. Generics (Go 1.18+)

Type parameters

// Generic function
func Sum[T int | float64](a, b T) T {
    return a + b
}

// With a type constraint interface
type Number interface {
    int | float64
}

func Multiply[T Number](a, b T) T {
    return a * b
}

// Generic types
type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(item T) {
    s.items = append(s.items, item)
}

func (s *Stack[T]) Pop() T {
    n := len(s.items) - 1
    item := s.items[n]
    s.items = s.items[:n]
    return item
}

15. Error Handling

No exceptions; functions return an error as a second value. The error type is a built-in interface.

type error interface {
    Error() string
}

func doSomething() (int, error) {
    if somethingWrong {
        return 0, errors.New("something failed") // from errors package
    }
    return 42, nil
}

result, err := doSomething()
if err != nil {
    // handle error
}
// use result

16. Concurrency Primitives

Goroutines

go someFunc(args)   // start new goroutine
go func() {
    // anonymous goroutine
}()

Channels

// Creating channels
ch := make(chan int)        // unbuffered
ch := make(chan int, 10)    // buffered

// Send and receive
ch <- 42          // send
value := <-ch     // receive

// Close channel (only by sender)
close(ch)

// Receive with open check
value, ok := <-ch   // ok is false if channel closed and drained

// Range over channel (loop until closed)
for v := range ch {
    // process v
}

// Select statement (like switch for channel operations)
select {
case v := <-ch1:
    // ...
case ch2 <- 42:
    // ...
default:
    // non-blocking
}

17. Built-in Functions

(These are part of the language, not a package)

Function Description
len(v) length of string, array, slice, map, channel
cap(v) capacity of slice, channel
make(T, ...) create slice, map, or channel (initialized)
new(T) allocate zero value of T, return *T
append(slice, elems...) append elements to slice
copy(dst, src) copy elements between slices
delete(m, key) delete key from map
close(ch) close channel
panic(v) stop normal execution, start panicking
recover() catch a panic inside a deferred function
complex(r, i), real(c), imag(c) complex number manipulation

Go Standard Library

Package Overview

Domain Packages Primary Use
I/O & File System os, io, io/fs, bufio, path/filepath, embed File operations, streams, directory walking, static files
String & Byte Manipulation strings, bytes, strconv, unicode, regexp Text processing, conversions, regular expressions
Networking & HTTP net, net/http, net/url TCP/UDP, HTTP client/server, URL parsing
Data Encoding encoding/json, encoding/xml, encoding/csv, encoding/base64 Serialization/deserialization
Concurrency & Synchronization sync, sync/atomic, context Goroutine coordination, atomic ops, cancellation
Time time Time, duration, timers, tickers, formatting
Math math, math/rand/v2 Mathematics, random numbers
Logging log, log/slog Logging (standard & structured)
Errors errors Error creation, wrapping, inspection
Testing & Benchmarking testing, testing/fstest Unit tests, benchmarks, fuzzing
Templates text/template, html/template Text and HTML generation
Command-Line Flags flag Parsing command-line arguments
Reflection reflect Runtime type introspection
Runtime Control runtime, runtime/debug Goroutine/GC control, memory stats, stack traces
Sorting & Slices slices, sort Generic slice operations, sorting
Maps maps (Go 1.21+) Generic map utilities
Hashing & Crypto crypto/sha256, crypto/md5, hash, crypto/rand Cryptographic hashes, secure random

1. I/O and File System

os: Operating System Interface

  • File operations: os.Open(name) (*File, error), os.Create(name) (*File, error), os.OpenFile(name, flag, perm) (flags like os.O_RDONLY, os.O_WRONLY, os.O_RDWR, os.O_CREATE, os.O_APPEND, os.O_TRUNC)
  • File info: os.Stat(name), os.Lstat(name), os.ReadDir(name) (returns []DirEntry)
  • Manipulation: os.Remove(name), os.Rename(old, new), os.Mkdir(name, perm), os.MkdirAll(path, perm), os.Chmod, os.Chown
  • Environment: os.Getenv(key), os.Setenv(key, value), os.Environ(), os.LookupEnv(key)
  • Process: os.Getpid(), os.Exit(code), os.Args (slice of command-line args)
  • File abstractions: os.Stdin, os.Stdout, os.Stderr (type *os.File)
  • Error sentinel: os.ErrNotExist, os.ErrPermission

io: Basic I/O Interfaces

  • Core interfaces: io.Reader (method Read(p []byte) (n int, err error)), io.Writer (Write(p []byte) (n int, err error)), io.Closer
  • Utilities:
    • io.Copy(dst Writer, src Reader) (written int64, err error) – copies until EOF or error.
    • io.ReadAll(r Reader) ([]byte, error) – reads all data into memory (since Go 1.16).
    • io.NopCloser(r Reader) ReadCloser – wraps a Reader as a ReadCloser.
    • io.MultiReader, io.MultiWriter
    • io.LimitReader(r Reader, n int64) Reader – reads at most n bytes.
    • io.TeeReader(r Reader, w Writer) Reader – duplicates reads to a writer.
  • Sentinel error: io.EOF (end of file)

io/fs: File System Interface (Go 1.16+)

  • Core types: fs.FS (Open method), fs.File (Stat, Read, Close), fs.FileInfo
  • Functions:
    • fs.ReadFile(fsys FS, name string) ([]byte, error) – convenient full-file read.
    • fs.ValidPath(name) bool
    • fs.WalkDir(fsys FS, root string, fn WalkDirFunc) error
    • fs.Glob(fsys FS, pattern string) (matches []string, err error)

bufio: Buffered I/O

  • Scanner: bufio.NewScanner(io.Reader) – line-by-line scanning (default); use Split for custom (e.g., bufio.ScanWords, bufio.ScanBytes). Methods: Scan() bool, Text() string, Err() error.
  • Reader: bufio.NewReader(rd io.Reader) with methods ReadString(delim byte), ReadBytes(delim byte), ReadLine(), Peek(n int).
  • Writer: bufio.NewWriter(w io.Writer) with Write, WriteString, Flush. bufio.NewWriterSize(w, size) for custom buffer size.

path/filepath: Cross-Platform Path Manipulation

  • Path manipulation: filepath.Join(elem ...string) string, filepath.Split(path) (dir, file), filepath.Ext(path), filepath.Base(path), filepath.Dir(path).
  • Walking: filepath.Walk(root string, fn filepath.WalkFunc) error – pre‑Go 1.16; prefer filepath.WalkDir (Go 1.16+) with fs.DirEntry for efficiency.
  • Matching: filepath.Glob(pattern) ([]string, error)
  • Clean and Abs: filepath.Clean(path), filepath.Abs(path)

embed: Embed Static Files (Go 1.16+)

Embed files and directories at compile time into the Go binary.

import "embed"

//go:embed hello.txt
var s string

//go:embed static/*
var staticFS embed.FS

The embed.FS implements fs.FS, so it can be used with http.FileServer, fs.ReadFile, etc.

2. Strings and Byte Slices

strings: String Operations

  • Search: Contains(s, substr), ContainsAny(s, chars), Count(s, substr)
  • Prefix/Suffix: HasPrefix(s, prefix), HasSuffix(s, suffix)
  • Index: Index(s, substr), LastIndex, IndexByte, IndexRune
  • Splitting/Joining: Split(s, sep), Fields(s) (whitespace), SplitN(s, sep, n), Join(a []string, sep)
  • Modification: ToLower(s), ToUpper(s), Trim(s, cutset), TrimSpace(s), TrimPrefix, TrimSuffix
  • Replace: Replace(s, old, new, n), ReplaceAll(s, old, new)
  • Building: strings.Builder – efficient mutable string builder. Methods: WriteString, WriteRune, String.
  • Other: Repeat(s, count), Compare(a, b) (rarely needed; use ==)

bytes: Byte Slice Operations

Mirrors the strings API for []byte:

  • bytes.Contains(b, subslice), bytes.Split(b, sep), bytes.HasPrefix(b, prefix), etc.
  • Buffer: bytes.Buffer – a byte buffer with Write, Read, String, Bytes, useful for building and reading byte sequences.
  • Clone: bytes.Clone(b) []byte (since Go 1.20) – deep copy.

strconv: String Conversions

  • String ↔ Integer:
    • strconv.Atoi(s string) (int, error), strconv.Itoa(i int) string
    • strconv.ParseInt(s, base, bitSize) (int64, error), strconv.FormatInt(i, base)
  • String ↔ Float:
    • strconv.ParseFloat(s string, bitSize int) (float64, error), strconv.FormatFloat(f, fmt, prec, bitSize)
  • String ↔ Bool:
    • strconv.ParseBool(s) (bool, error), strconv.FormatBool(b)
  • Quoting: strconv.Quote(s) string (adds quotes), strconv.Unquote(s) (string, error)
  • Append functions: Append versions for efficiency (strconv.AppendInt, etc.)

unicode: Unicode Character Classification

  • unicode.IsDigit(r), unicode.IsLetter(r), unicode.IsSpace(r), unicode.IsUpper(r), unicode.IsLower(r)
  • unicode.ToUpper, unicode.ToLower
  • unicode.UTF8 sub‑package for more specific UTF‑8 checks.

regexp: Regular Expressions

  • Compilation: regexp.Compile(expr string) (*Regexp, error), regexp.MustCompile(expr) (panics on error)
  • Matching: MatchString(pattern string, s string) bool (convenience), Regexp.MatchString(s string) bool
  • Finding: FindString(s), FindStringSubmatch(s), FindAllString(s, n), FindAllStringSubmatch(s, n)
  • Replace: ReplaceAllString(src, repl), ReplaceAllLiteralString
  • Splitting: Split(s string, n int) []string

3. Networking and HTTP

net: Core Networking

  • Dial/Listen:
    • net.Dial(network, address) (e.g., "tcp", "golang.org:80") → net.Conn
    • net.Listen(network, address)net.Listener
  • Connection: Conn interface (Read, Write, Close, LocalAddr, RemoteAddr, SetDeadline, etc.)
  • Resolver: net.LookupHost(host), net.LookupIP(host), net.ResolveIPAddr, net.ResolveTCPAddr
  • Utilities: net.JoinHostPort(host, port), net.SplitHostPort(hostport)
  • Interfaces: net.Interfaces(), net.InterfaceAddrs()
  • IP type: net.ParseIP(s), net.IP methods (To4, String, Equal)

net/http: HTTP Client and Server

  • Client (Quick):
    • http.Get(url)*http.Response, error
    • http.Post(url, contentType, body), http.PostForm(url, data url.Values)
  • Client (Custom):
    • http.Client with Transport, Timeout, CheckRedirect.
    • client.Do(req), client.Get(url), client.Post(...)
  • Request: http.NewRequest(method, url, body) → set headers, etc.
  • Response: res.Body (io.ReadCloser), res.StatusCode, res.Header, read with io.ReadAll.
    • Important: Always close the response body (defer res.Body.Close())
  • Server:
    • http.HandleFunc(pattern, handlerFunc) – register a handler.
    • http.ListenAndServe(addr, handler) – start server; nil uses default mux.
    • Custom http.Server with fields like Addr, Handler, ReadTimeout, WriteTimeout.
  • Request (handler): r.Method, r.URL.Path, r.URL.Query(), r.Body, r.Header, r.FormValue(key), r.ParseForm()
  • ResponseWriter: w.WriteHeader(statusCode), w.Write(data), w.Header().Set(...)
  • Middleware pattern: wrap http.Handler via http.HandlerFunc adapter.
  • ServeMux enhancements: Since Go 1.22, pattern matching supports GET, POST, path parameters with {name}, http.NewServeMux().

net/url: URL Parsing

  • url.Parse(rawURL) (*URL, error) – parse and decompose URL (Scheme, Host, Path, RawQuery, etc.)
  • url.Query() Values – returns url.Values map.
  • Values.Get(key), Values.Add(key, value), Values.Encode() → query string.

4. Data Encoding

encoding/json: JSON

  • Struct → JSON: json.Marshal(v) ([]byte, error), json.MarshalIndent(v, prefix, indent)
  • JSON → Struct: json.Unmarshal(data []byte, v interface{}) error
  • Streaming: json.NewEncoder(w io.Writer) with Encode(v), json.NewDecoder(r io.Reader) with Decode(v).
  • Struct tags: json:"fieldname,omitempty,string", can hide fields with json:"-"
  • Raw messages: json.RawMessage to delay decoding.
  • Decoder: DisallowUnknownFields(), UseNumber() (to decode numbers as json.Number instead of float64).

encoding/xml: XML

  • xml.Marshal, xml.Unmarshal
  • Struct tags: xml:"name,attr,omitempty" and xml:",chardata"
  • xml.Decoder (streaming) with Token() for large files.

encoding/csv: CSV

  • Reader: csv.NewReader(r io.Reader), options like Comma, LazyQuotes. Read() (record []string, err error), ReadAll() (records [][]string, err error)
  • Writer: csv.NewWriter(w io.Writer), Write(record), Flush, Comma setting.

encoding/base64: Base64

  • base64.StdEncoding.EncodeToString(src), DecodeString(s)
  • base64.URLEncoding for URL-safe variant.

5. Concurrency and Synchronization

sync: Synchronization Primitives

  • Mutex: sync.Mutex with Lock() / Unlock(). sync.RWMutex for multiple readers (RLock/RUnlock).
  • WaitGroup: var wg sync.WaitGroup. wg.Add(delta), wg.Done(), wg.Wait().
  • Once: sync.OnceDo(f func()) ensures f runs exactly once.
  • Map: sync.Map – concurrent map with Load, Store, LoadOrStore, Delete, Range. Use only when needed; prefer regular maps with mutexes unless profiling shows contention.
  • Pool: sync.Pool – temporary object cache; Get(), Put(x); useful to reduce allocations.
  • Cond: sync.NewCond(&mu) for broadcast/signal patterns.

sync/atomic: Atomic Operations

  • Low-level atomic memory operations on int32, int64, uint32, uint64, pointer, etc.
  • Functions: atomic.AddInt32(&v, delta), atomic.LoadInt32(&v), atomic.StoreInt32(&v, new), atomic.CompareAndSwapInt32(&v, old, new).
  • Type-safe generics (Go 1.19+): atomic.Int32, atomic.Int64, atomic.Pointer[T] with methods like Add, Load, Store, CompareAndSwap. Prefer these over raw functions.

context: Request-Scoped Values, Cancellation

  • Creation:
    • context.Background() – root context for main, init, etc.
    • context.TODO() – placeholder.
    • context.WithCancel(parent) (ctx, cancel) – create cancellable context; call cancel() to release resources.
    • context.WithTimeout(parent, duration) / WithDeadline(parent, time.Time) – auto-cancel after time.
    • context.WithValue(parent, key, val) – carry request-scoped data (use specific key types, not string).
  • Usage:
    • ctx.Done() <-chan struct{} – closed when cancelled/timed out.
    • ctx.Err() – returns reason (context.Canceled or context.DeadlineExceeded).
    • ctx.Value(key) interface{} – retrieve value.
  • Rule: Pass context as first argument, typically named ctx.

6. Time

  • Instant: time.Now(), time.Date(year, month, day, hour, min, sec, nsec, loc)
  • Duration: time.Duration (int64 nanoseconds). Constants: time.Nanosecond, time.Microsecond, time.Millisecond, time.Second, time.Minute, time.Hour.
  • Arithmetic: t.Add(d), t.Sub(u) Duration, time.Since(t) Duration
  • Comparison: t.Before(u), t.After(u), t.Equal(u)
  • Formatting/Parsing:
    • t.Format(layout string) – reference layout must be "Mon Jan 2 15:04:05 MST 2006" (fixed date/time).
    • Predefined layouts: time.RFC3339, time.RFC822, time.Kitchen, etc.
    • time.Parse(layout, value string) (Time, error).
  • Sleep: time.Sleep(d Duration)
  • Ticker: time.NewTicker(d) – returns channel C that fires repeatedly. ticker.Stop().
  • Timer: time.NewTimer(d) – fires once; stop with timer.Stop(), reset with timer.Reset(d). time.After(d) returns channel (for simple cases).
  • Location: time.LoadLocation(name), time.FixedZone, t.In(loc).

7. Math and Random

math: Mathematical Functions and Constants

  • Constants: math.Pi, math.E, math.MaxFloat64, math.MinInt64...
  • Functions: math.Abs, math.Pow, math.Sqrt, math.Sin, math.Cos, math.Log, math.Exp, math.Floor, math.Ceil, math.Max, math.Min (the last two are generic in Go 1.21+, otherwise math.Max/Min for floats).

math/rand/v2: Pseudorandom Numbers (Go 1.22+)

  • Source: rand.New(rand.NewPCG(seed1, seed2)) (PCG is default). For reproducibility, use a custom source.
  • Global random (top-level): seed automatically (no need to call Seed()).
  • Ints: rand.Int(), rand.IntN(n) (0 ≤ x < n), rand.Int64(), rand.Uint64()
  • Floats: rand.Float64() (0.0 ≤ x < 1.0), rand.Float32()
  • Slices: rand.Shuffle(n int, swap func(i, j int)), rand.Perm(n) []int
  • Reader: rand.ChaCha8 as crypto-like random for shuffle. Use crypto/rand for security-sensitive randomness.

8. Logging

log: Standard Logger

  • log.Println(v ...), log.Printf(format, v ...), log.Fatal(v ...), log.Fatalf, log.Panic
  • log.SetOutput(w io.Writer), log.SetFlags(flag int) (e.g., log.Ldate|log.Ltime|log.Lshortfile)
  • log.New(out, prefix, flag) to create custom loggers.

log/slog: Structured Logging (Go 1.21+)

  • Logger: slog.New(slog.NewJSONHandler(w, nil)), slog.NewTextHandler
  • Levels: slog.Debug, slog.Info, slog.Warn, slog.Error. Use slog.Info("msg", "key", value).
  • Default logger: slog.SetDefault(logger), slog.Info(...)
  • With attributes: logger.With("service", "myapp") to add common keys.
  • Context integration: slog.InfoContext(ctx, ...) carries context values.
  • Handler options: &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: true}

9. Errors

  • Creation: errors.New(text string) error, fmt.Errorf("...: %w", err) wraps an error.
  • Inspection:
    • errors.Is(err, target) bool – checks if err is target (following the chain).
    • errors.As(err, target interface{}) bool – extracts the first error in chain that matches target type and sets target.
  • Unwrap: errors.Unwrap(err) error – returns next wrapped error.
  • New helpers (Go 1.20+): errors.Join(errs ...error) – combines multiple errors into one.

10. Testing

testing: Test Framework

  • Test function: func TestXxx(t *testing.T) (must start with Test). Inside:
    • t.Error(args...), t.Errorf(format, args...) – mark test failed but continue.
    • t.Fatal(args...), t.Fatalf(format, args...) – fail now.
    • t.Log, t.Logf – log only if test fails or -v flag.
    • t.Run(name, func(t *testing.T)) – sub‑tests.
    • t.Parallel() – run in parallel with other parallel tests.
    • t.Cleanup(func()) – register a cleanup function.
  • Benchmark: func BenchmarkXxx(b *testing.B), inside loop for i := 0; i < b.N; i++ { ... }. b.ReportAllocs().
  • Fuzzing (Go 1.18+): func FuzzXxx(f *testing.F). Add seeds with f.Add(...), then f.Fuzz(func(t *testing.T, ...) { ... }).
  • Helpers: t.Helper() marks a function as a test helper (for better error trace).
  • Temp directory: t.TempDir() – creates a temporary directory cleaned up after test.
  • Skipping: t.Skip(), t.Skipf().

testing/fstest: Testing File Systems

  • fstest.TestFS(fsys fs.FS, expected ...string) – verifies a file system contains the expected files.

11. Templates

text/template: Generic Text Templates

  • Creation: tmpl, err := template.New("name").Parse("Hello {{.}}")
  • Execution: tmpl.Execute(w io.Writer, data) error
  • Actions: {{.}}, {{.Field}}, {{.Method}}, {{if .}}...{{end}}, {{range $i, $v := .}}...{{end}}
  • Functions: template.FuncMap to add custom functions.
  • Template nesting: {{template "name"}} or {{template "name" .}}

html/template: HTML-Safe Templates

  • Identical API to text/template but contextually escapes output to prevent XSS. Always use it for HTML generation.

12. Command-Line Flags

  • Define flags:
    • intPtr := flag.Int("n", 0, "help"), strPtr := flag.String("name", "", "help"), boolPtr := flag.Bool("verbose", false, "help")
    • Alternatively, bind to existing variable with flag.IntVar(&var, "name", value, usage)
  • Parse: flag.Parse() (must be called after all flag definitions).
  • Args: flag.Args() returns non-flag arguments; flag.NArg() and flag.Arg(i).
  • Custom flags: implement flag.Value interface.

13. Reflection

  • Get type: reflect.TypeOf(i), reflect.ValueOf(i)
  • Type info: t.Kind() (e.g., reflect.Struct, reflect.Slice, reflect.Ptr, etc.), t.Name(), t.NumField(), t.Field(i)
  • Value manipulation (settability): v.Elem() for pointer dereference, v.CanSet(), v.SetInt(...), v.FieldByName("Name")
  • Deep equality: reflect.DeepEqual(x, y) bool – compares any two values recursively.

14. Runtime Control and Diagnostics

runtime: Go Runtime

  • Goroutines: runtime.NumGoroutine() int, runtime.Goexit() (terminate current goroutine)
  • CPU: runtime.NumCPU() int, runtime.GOMAXPROCS(n int) int (set/get maximum number of CPUs used)
  • Memory: runtime.ReadMemStats(&m) – populate runtime.MemStats with memory allocation stats.
  • GC: runtime.GC() – force garbage collection.
  • Stack: runtime.Caller(skip int) (pc uintptr, file string, line int, ok bool) for stack introspection.
  • GOOS/GOARCH: runtime.GOOS, runtime.GOARCH – compile-time constants.

runtime/debug: Debugging Utilities

  • debug.PrintStack() – print stack trace.
  • debug.SetMaxStack(bytes) – set max goroutine stack.
  • debug.FreeOSMemory() – force scavenge memory to OS.

15. Slices, Maps, and Sorting

slices: Generic Slice Functions (Go 1.21+)

  • slices.Contains(s, v) – check existence.
  • slices.Clone(s) – shallow copy.
  • slices.Delete(s, i, j) – remove range.
  • slices.Index, slices.Insert, slices.Replace, slices.Reverse
  • slices.Sort(s), slices.SortFunc(s, cmp), slices.BinarySearch(s, target) (slice must be sorted).

maps: Generic Map Functions (Go 1.21+)

  • maps.Clone(m) – shallow copy.
  • maps.Copy(dst, src) – copy all entries.
  • maps.DeleteFunc(m, del func(k, v) bool) – delete entries satisfying condition.
  • maps.Equal(m1, m2), maps.EqualFunc(m1, m2, eq) – compare maps.

sort: Sorting

  • Sort slice: sort.Slice(slice, func(i, j int) bool) – general method.
  • Pre‑1.21 style: sort.Ints, sort.Strings, sort.Float64s, sort.Sort(data sort.Interface).
  • Search: sort.Search(n int, f func(i int) bool) int – binary search.

16. Cryptography (Selected Essentials)

crypto/sha256, crypto/sha512: SHA Hashes

  • sha256.Sum256(data []byte) [32]byte, sha256.New() (returns hash.Hash)
  • Hash interface: io.Writer for feeding data, Sum(b []byte) []byte, Reset()

crypto/md5: MD5 (non-cryptographic checksums)

  • md5.Sum(data) [16]byte, md5.New()

crypto/rand: Cryptographically Secure Random

  • rand.Read(b []byte) (n int, err error) – fill slice with random bytes.
  • rand.Int(rand io.Reader, max *big.Int) – random integer.

hash: Hash Utilities

  • hash.New() pattern with io.WriteString(h, "data"), then h.Sum(nil) to finalize.

Go CLI Tools

1. The go Command: The Main Hub

The go command is the central tool for managing Go source code, covering the entire development lifecycle from building and testing to dependency management.

Getting Help

Command Description
go help List all available go subcommands.
go help <command> Get detailed help for a specific command (e.g., go help build).
go help <topic> Get help on a specific topic (e.g., go help modules).
go doc <package/symbol> Show documentation for a package or symbol (e.g., go doc fmt.Printf).
go version Print the installed Go version.

Core Subcommands

Command Description & Common Usage
go build Compile packages and dependencies. go build -o myapp ./cmd/server
go run Compile and run a Go program in one step (binary is temporary). go run main.go
go install Compile and install packages and dependencies (places binary in $GOPATH/bin).
go test Run tests. go test ./... runs all tests in the module.
go vet Report suspicious constructs and potential bugs. go vet ./...
go fmt Format Go source code using gofmt. go fmt ./...
go mod Module maintenance (init, tidy, download, etc.).
go get Add dependencies to the current module and install them. go get golang.org/x/tools/cmd/goimports
go list List packages or modules. go list -m all lists all dependencies.
go clean Remove object files and cached files. go clean -cache
go env Print Go environment information. go env GOPATH
go generate Generate Go files by processing source (uses //go:generate directives).
go fix Update packages to use new APIs (useful for migration).
go work Workspace maintenance for multi-module projects.
go bug Start a bug report, opening a browser with helpful system info.

Other Useful Subcommands & Features

  • go tool: Run a specific Go tool. Use go tool to see the list.
  • go telemetry: Manage telemetry data and settings.
  • go completion bash: Generate an autocompletion script for your shell.

💡 Pro Tip: You can set the GOEXPERIMENT environment variable to enable experimental features from the command line. For example, GOEXPERIMENT=loopvar go test ./....

2. go mod: Module Management (Go 1.11+)

The go mod command is the cornerstone of modern Go dependency management.

go mod Subcommands

Subcommand Description
go mod init <module-path> Initialize a new module, creating a go.mod file.
go mod tidy Add missing and remove unused modules, updating go.mod and go.sum.
go mod download Download modules to the local cache.
go mod vendor Create a vendor directory containing copies of all dependencies.
go mod verify Verify that downloaded dependencies are unchanged since download.
go mod why Explain why a package or module is needed.
go mod graph Print the module requirement graph.
go mod edit Edit go.mod from a script or command line.

go.mod Tool Directive (Go 1.24+)

A new feature for managing CLI tool dependencies directly in go.mod.

  • Add a tool dependency: go get -tool golang.org/x/tools/cmd/stringer
  • Run the tool: go tool stringer (instead of installing globally)

3. Code Quality & Analysis Tools

These tools are separate from the go command but are essential for a professional development workflow.

gofmt (Code Formatter)

  • The standard Go code formatter.
  • Format a file and print to stdout: gofmt main.go
  • Format and overwrite the file: gofmt -w main.go
  • Format all files in a directory recursively: gofmt -w .

goimports (Import Manager & Formatter)

  • A superset of gofmt that automatically manages import lines.
  • Install: go install golang.org/x/tools/cmd/goimports@latest
  • Use as a replacement for gofmt: goimports -w main.go

go vet (Static Analyzer)

  • Examines source code for common suspicious constructs (e.g., bad Printf calls).
  • Run on current package: go vet
  • Run on all packages in module: go vet ./...
  • List all available checks: go tool vet help
  • Run a specific check: go vet -printf=false ./... (runs all checks except printf)
  • Available checks include: asmdecl, assign, atomic, bools, buildtag, cgocall, composites, copylocks, httpresponse, loopclosure, lostcancel, nilfunc, printf, shadow, shift, structtag, tests, unreachable, unsafeptr, and many more.

golangci-lint (The Meta-Linter)

  • A fast aggregator of many linters (incl. govet, gofmt, errcheck).
  • Quick start: golangci-lint run
  • Run with specific linters: golangci-lint run --disable-all -E errcheck,govet
  • Help and options: golangci-lint run -h

4. Compilation Toolchain (go tool)

These lower-level tools are invoked using go tool <tool-name>.

Tool Description
go tool compile Compile a single Go package (used by go build).
go tool link Link compiled packages into an executable (used by go build).
go tool asm Assemble an assembly source file. go tool asm -o output.o input.s
go tool cgo Generate Go code that calls C code.
go tool pprof Interpret and display profiles for performance analysis.
go tool objdump Disassemble an executable.
go tool nm List symbols in an object file or archive.
go tool fix Rewrite legacy Go code to use newer APIs.
go tool dist Bootstrap, build, and test the Go distribution itself.

5. Quick Reference Summary

Category Command Key Action
Build & Run go build, go run, go install Compile and execute code.
Testing go test Execute unit tests.
Code Quality gofmt, go vet, golangci-lint Format, analyze, and lint code.
Documentation go doc Access offline documentation.
Module Mgmt go mod Manage dependencies and module structure.
Toolchain go tool Access low-level compilers, linkers, etc.
Misc. go env, go list, go clean Inspect environment, list packages, and clean caches.

Installation & Setup

  • Install Go: Download from go.dev and follow the instructions.
  • Add to PATH: Ensure $GOPATH/bin is in your system's PATH environment variable to easily run installed tools.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment