Skip to main content

Go Reference

v1.0.2reference

Searchable Go quick reference — goroutines, channels, error handling, generics, and standard library.

Quick-reference for Go — covers built-in types, slices, maps, channels, goroutines, interfaces, error handling, and standard library packages (fmt, io, net/http, sync) with copy-ready code snippets.

How to use
  • Search by keyword (e.g. "goroutine", "channel", "defer") to jump to the relevant entry.
  • Click any snippet to copy it and adapt it in your Go file.
  • Browse the Standard Library section to find common packages and their most-used functions.
  • Use the Concurrency section for goroutine, channel, and sync.Mutex patterns.

23 results

go func()

Goroutines & Channelsbuiltin

go func() { ... }()

Launch a lightweight goroutine.

go func() {
    result := compute()
    ch <- result
}()

chan

Goroutines & Channelsbuiltin

ch := make(chan T [, bufferSize])

Create a typed channel for goroutine communication.

ch := make(chan string, 10) // buffered
ch <- "hello"               // send
msg := <-ch                 // receive

select

Goroutines & Channelsbuiltin

select { case <-ch: ... default: ... }

Multiplex on multiple channel operations.

select {
case msg := <-ch1:
    fmt.Println(msg)
case ch2 <- data:
    fmt.Println("sent")
case <-time.After(time.Second):
    fmt.Println("timeout")
}

errors.Is()

Error Handlingerrors

func Is(err, target error) bool

Reports whether any error in err's chain matches target.

if errors.Is(err, os.ErrNotExist) {
    log.Println("file not found")
}

errors.As()

Error Handlingerrors

func As(err error, target any) bool

Finds first error in chain matching target type.

var pathErr *os.PathError
if errors.As(err, &pathErr) {
    fmt.Println("path:", pathErr.Path)
}

fmt.Errorf %w

Error Handlingfmt

fmt.Errorf("... %w", err)

Wrap an error with additional context.

return fmt.Errorf("reading config: %w", err)

errors.Join()

Error Handlingerrors

func Join(errs ...error) error

Combine multiple errors into one (Go 1.20+).

err := errors.Join(validate(), authorize(), execute())

slices.Sort()

Std Libraryslices

func Sort[S ~[]E, E cmp.Ordered](x S)

Sort a slice of any ordered type (Go 1.21+).

nums := []int{3, 1, 4, 1, 5}
slices.Sort(nums)

maps.Keys()

Std Librarymaps

func Keys[M ~map[K]V, K comparable, V any](m M) []K

Returns the keys of a map (Go 1.21+).

keys := maps.Keys(myMap)
slices.Sort(keys)

slog

Std Librarylog/slog

slog.Info("msg", "key", value)

Structured logging in the standard library (Go 1.21+).

slog.Info("request",
    "method", r.Method,
    "path", r.URL.Path,
    "duration", time.Since(start),
)

http.ServeMux

Std Librarynet/http

mux.HandleFunc("GET /path", handler)

Enhanced ServeMux with method+pattern routing (Go 1.22+).

mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", getUser)
mux.HandleFunc("POST /users", createUser)

sync.Map

Std Librarysync

var m sync.Map

Concurrent-safe map that doesn't require explicit locking.

var cache sync.Map
cache.Store("key", value)
if v, ok := cache.Load("key"); ok {
    fmt.Println(v)
}

Type parameters

Genericsbuiltin

func Name[T constraint](param T) T

Generic functions with type parameters (Go 1.18+).

func Min[T cmp.Ordered](a, b T) T {
    if a < b { return a }
    return b
}

Type constraints

Genericsbuiltin

type Number interface { ~int | ~float64 }

Define type constraints for generics.

type Number interface {
    ~int | ~int64 | ~float64
}
func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums { total += n }
    return total
}

t.Run()

Testingtesting

func (t *T) Run(name string, f func(t *T)) bool

Run a subtest for table-driven tests.

tests := []struct{
    name string; input int; want int
}{
    {"positive", 5, 25},
    {"zero", 0, 0},
}
for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        if got := square(tt.input); got != tt.want {
            t.Errorf("got %d, want %d", got, tt.want)
        }
    })
}

t.Parallel()

Testingtesting

func (t *T) Parallel()

Signal that this test can run in parallel.

func TestFetch(t *testing.T) {
    t.Parallel()
    // ... test code
}

sync.WaitGroup

Concurrency Patternssync

var wg sync.WaitGroup

Wait for a collection of goroutines to finish.

var wg sync.WaitGroup
for _, url := range urls {
    wg.Add(1)
    go func(u string) {
        defer wg.Done()
        fetch(u)
    }(url)
}
wg.Wait()

errgroup.Group

Concurrency Patternsgolang.org/x/sync/errgroup

g, ctx := errgroup.WithContext(ctx)

Goroutine group with error propagation and context cancellation.

g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return fetchUser(ctx) })
g.Go(func() error { return fetchOrders(ctx) })
if err := g.Wait(); err != nil {
    log.Fatal(err)
}

os.ReadFile()

I/Oos

func ReadFile(name string) ([]byte, error)

Read entire file into memory.

data, err := os.ReadFile("config.json")
if err != nil { log.Fatal(err) }

json.Marshal()

I/Oencoding/json

func Marshal(v any) ([]byte, error)

Encode a Go value to JSON.

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}
data, _ := json.Marshal(User{"Alice", "a@b.com"})

json.NewDecoder()

I/Oencoding/json

func NewDecoder(r io.Reader) *Decoder

Streaming JSON decoder for readers.

var user User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
    http.Error(w, err.Error(), 400)
}

context.WithCancel()

Contextcontext

func WithCancel(parent Context) (Context, CancelFunc)

Create a cancellable context.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go worker(ctx)

context.WithTimeout()

Contextcontext

func WithTimeout(parent Context, timeout Duration) (Context, CancelFunc)

Create a context that auto-cancels after a timeout.

ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
result, err := fetchWithContext(ctx)