Go Reference
v1.0.2referenceSearchable 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 & Channelsbuiltingo func() { ... }()
Launch a lightweight goroutine.
go func() {
result := compute()
ch <- result
}()chan
Goroutines & Channelsbuiltinch := 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 & Channelsbuiltinselect { 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 Handlingerrorsfunc 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 Handlingerrorsfunc 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 Handlingfmtfmt.Errorf("... %w", err)
Wrap an error with additional context.
return fmt.Errorf("reading config: %w", err)errors.Join()
Error Handlingerrorsfunc Join(errs ...error) error
Combine multiple errors into one (Go 1.20+).
err := errors.Join(validate(), authorize(), execute())
slices.Sort()
Std Libraryslicesfunc 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 Librarymapsfunc 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/slogslog.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/httpmux.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 Librarysyncvar 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
Genericsbuiltinfunc 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
Genericsbuiltintype 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()
Testingtestingfunc (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()
Testingtestingfunc (t *T) Parallel()
Signal that this test can run in parallel.
func TestFetch(t *testing.T) {
t.Parallel()
// ... test code
}sync.WaitGroup
Concurrency Patternssyncvar 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/errgroupg, 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/Oosfunc 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/jsonfunc 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/jsonfunc 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()
Contextcontextfunc WithCancel(parent Context) (Context, CancelFunc)
Create a cancellable context.
ctx, cancel := context.WithCancel(context.Background()) defer cancel() go worker(ctx)
context.WithTimeout()
Contextcontextfunc 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)