📖 Guide

Go (Golang) Cheat Sheet — Complete Reference

Complete Go reference — syntax, types, functions, concurrency, error handling, and common patterns. Searchable and organized.

207 commands across 11 categories

Basics

CommandDescription
package main
Declare the main package (entry point)
import "fmt"
Import a single package
import ( "fmt" "os" )
Import multiple packages with grouped import
func main() { }
Entry point function — executed when program runs
var x int
Declare a variable with explicit type
var x int = 10
Declare and initialize a variable
var x = 10
Declare with type inference
x := 10
Short variable declaration (inside functions only)
var x, y int = 1, 2
Declare multiple variables of the same type
const Pi = 3.14159
Declare a constant
const ( A = 1 B = 2 )
Declare multiple constants in a block
const ( A = iota B C )
Use iota for auto-incrementing constants (0, 1, 2)
_ = unusedVar
Blank identifier — discard a value to avoid unused variable error
// comment
Single-line comment
/* block comment */
Multi-line block comment
fmt.Println(x)
e.g. fmt.Println("Hello, World!")
Print a value with newline
fmt.Printf("%s is %d\n", name, age)
Formatted print (like C printf)
fmt.Sprintf(...)
e.g. msg := fmt.Sprintf("Hi %s", name)
Format and return a string (no print)

Types

CommandDescription
bool
Boolean type — true or false
int, int8, int16, int32, int64
Signed integer types
uint, uint8, uint16, uint32, uint64
Unsigned integer types
float32, float64
Floating-point types
complex64, complex128
Complex number types
string
Immutable sequence of bytes (UTF-8)
byte
Alias for uint8 — raw byte data
rune
Alias for int32 — represents a Unicode code point
var a [5]int
Declare a fixed-size array of 5 ints
a := [3]int{1, 2, 3}
Array literal
var s []int
Declare a slice (dynamic array)
s := []int{1, 2, 3}
Slice literal
s := make([]int, 5)
e.g. s := make([]int, 5, 10) // len=5, cap=10
Create a slice with length 5
s = append(s, 4, 5)
Append elements to a slice
s2 := s[1:3]
Slice a slice (indices 1 to 2)
len(s)
Length of a slice, array, map, string, or channel
cap(s)
Capacity of a slice or channel
copy(dst, src)
Copy elements between slices
m := map[string]int{}
Declare an empty map
m := map[string]int{"a": 1, "b": 2}
Map literal
m := make(map[string]int)
Create a map with make
m["key"] = 42
Set a map value
v := m["key"]
Get a map value
v, ok := m["key"]
Get value with existence check (comma ok idiom)
delete(m, "key")
Delete a key from a map
type MyInt int
Define a custom type based on an existing type
type Alias = int
Type alias (same underlying type)

Control Flow

CommandDescription
if x > 0 { }
Basic if statement (no parentheses needed)
if x := compute(); x > 0 { }
If with init statement
if x > 0 { } else if x == 0 { } else { }
If / else if / else chain
for i := 0; i < 10; i++ { }
Classic C-style for loop
for x < 100 { }
While-style loop (for with condition only)
for { }
Infinite loop
for i, v := range slice { }
Range over slice (index and value)
for k, v := range m { }
Range over map (key and value)
for i, c := range str { }
Range over string (index and rune)
for range 10 { }
Range over integer (Go 1.22+)
break
Exit the innermost loop
continue
Skip to next iteration
switch x { case 1: case 2: default: }
Switch statement (no fallthrough by default)
switch { case x > 0: case x < 0: }
Switch without expression (like if/else chain)
fallthrough
Explicitly fall through to next case in switch
defer fmt.Println("done")
Defer a function call to run when enclosing function returns
defer file.Close()
Common pattern: defer resource cleanup
goto label
Jump to a label (rarely used)

Functions

CommandDescription
func add(a, b int) int { return a + b }
Basic function with parameters and return value
func swap(a, b int) (int, int) { return b, a }
Function with multiple return values
func divide(a, b float64) (float64, error)
Function returning value and error (idiomatic)
func greet(name string) (msg string) { msg = "Hi " + name return }
Named return values with naked return
func sum(nums ...int) int
e.g. sum(1, 2, 3)
Variadic function — accepts any number of ints
sum(nums...)
Spread a slice into a variadic function
f := func(x int) int { return x * 2 }
Anonymous function / function literal
func() { fmt.Println("now") }()
Immediately invoked function expression (IIFE)
func counter() func() int { n := 0 return func() int { n++; return n } }
Closure — function that captures outer variables
func(w http.ResponseWriter, r *http.Request)
Common HTTP handler function signature
type Handler func(string) error
Define a function type
func init() { }
Package initializer — runs before main(), can have multiple per file

Structs & Methods

CommandDescription
type Person struct { Name string Age int }
Define a struct type
p := Person{Name: "Alice", Age: 30}
Create a struct instance with named fields
p := Person{"Alice", 30}
Create a struct with positional fields
p.Name
Access a struct field
&Person{Name: "Bob"}
Create a pointer to a struct
new(Person)
Allocate a zeroed struct and return pointer
type Address struct { City string } type Person struct { Name string Address }
Embedded struct (composition)
func (p Person) Greet() string { return "Hi, " + p.Name }
Method with value receiver
func (p *Person) SetAge(a int) { p.Age = a }
Method with pointer receiver (can modify struct)
p.Greet()
Call a method on a struct
type Config struct { Host string `json:"host"` Port int `json:"port,omitempty"` }
Struct tags for JSON serialization

Interfaces

CommandDescription
type Reader interface { Read(p []byte) (n int, err error) }
Define an interface
// implicit implementation
Types implement interfaces implicitly — no 'implements' keyword
var r io.Reader = &MyReader{}
Assign concrete type to interface variable
interface{}
Empty interface — satisfied by any type (like any)
any
Alias for interface{} (Go 1.18+)
v, ok := i.(string)
Type assertion with ok check
s := i.(string)
Type assertion (panics if wrong type)
switch v := i.(type) { case string: case int: }
Type switch
type ReadWriter interface { Reader Writer }
Interface embedding (composition)
func process(r io.Reader) { }
Accept interface as parameter (program to interfaces)
type Stringer interface { String() string }
fmt.Stringer interface — custom string representation
type error interface { Error() string }
Built-in error interface

Error Handling

CommandDescription
if err != nil { return err }
Idiomatic error check and propagation
errors.New("something failed")
Create a simple error
fmt.Errorf("failed to load %s: %w", name, err)
Create a formatted error with wrapping (%w)
errors.Is(err, os.ErrNotExist)
Check if error matches a specific error value (unwraps)
errors.As(err, &target)
Check if error matches a specific type (unwraps)
errors.Unwrap(err)
Get the wrapped error
type MyError struct { Code int Msg string } func (e *MyError) Error() string { return e.Msg }
Custom error type implementing error interface
panic("fatal error")
Trigger a panic (stops normal execution)
defer func() { if r := recover(); r != nil { fmt.Println("recovered:", r) } }()
Recover from a panic in a deferred function
log.Fatal(err)
Log error and exit with os.Exit(1)
log.Fatalf("error: %v", err)
Formatted log and exit

Goroutines & Channels

CommandDescription
go myFunc()
Start a goroutine (concurrent lightweight thread)
go func() { // ... }()
Start a goroutine with anonymous function
ch := make(chan int)
Create an unbuffered channel
ch := make(chan int, 10)
Create a buffered channel with capacity 10
ch <- 42
Send a value to a channel
v := <-ch
Receive a value from a channel
close(ch)
Close a channel (no more sends)
for v := range ch { }
Receive values until channel is closed
v, ok := <-ch
Receive with closed check (ok is false if closed)
select { case v := <-ch1: case ch2 <- x: default: }
Select — wait on multiple channel operations
ch := make(chan<- int)
Send-only channel type
ch := make(<-chan int)
Receive-only channel type
var wg sync.WaitGroup
WaitGroup — wait for goroutines to finish
wg.Add(1)
Increment WaitGroup counter
defer wg.Done()
Decrement WaitGroup counter (call in goroutine)
wg.Wait()
Block until WaitGroup counter reaches zero
var mu sync.Mutex mu.Lock() defer mu.Unlock()
Mutex — mutual exclusion lock
var once sync.Once once.Do(func() { })
Run a function exactly once (thread-safe)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel()
Context with timeout for goroutine cancellation
ctx, cancel := context.WithCancel(context.Background())
Context with manual cancellation

Packages & Modules

CommandDescription
go mod init <module>
e.g. go mod init github.com/user/project
Initialize a new Go module
go mod tidy
Add missing and remove unused dependencies
go get <package>
e.g. go get github.com/gin-gonic/gin
Add a dependency
go get <package>@v1.2.3
Add a specific version of a dependency
go get -u <package>
Update a dependency to latest
go install <package>
e.g. go install golang.org/x/tools/gopls@latest
Build and install a Go binary
go build
Compile the package in current directory
go build -o <name>
Compile and set output binary name
go run main.go
Compile and run a Go file
go run .
Compile and run current package
go vet ./...
Run static analysis on all packages
go fmt ./...
Format all Go source files
go doc fmt.Println
Show documentation for a symbol
go list ./...
List all packages in module
go work init
Initialize a workspace (multi-module development)
GOOS=linux GOARCH=amd64 go build
Cross-compile for a different OS/arch

Testing

CommandDescription
func TestAdd(t *testing.T) { }
Define a test function (must start with Test)
t.Error("failed")
Report a test failure but continue
t.Errorf("got %d, want %d", got, want)
Report a formatted test failure
t.Fatal("fatal")
Report a failure and stop the test immediately
t.Run("subtest", func(t *testing.T) { })
Run a subtest
t.Parallel()
Mark test to run in parallel with other parallel tests
t.Skip("skipping")
Skip a test
t.Helper()
Mark function as test helper (improves error output)
go test ./...
Run all tests in module
go test -v ./...
Run tests with verbose output
go test -run TestAdd ./...
Run tests matching a regex
go test -count=1 ./...
Run tests without caching
go test -race ./...
Run tests with race detector
go test -cover ./...
Run tests with coverage report
go test -coverprofile=cover.out ./...
Generate coverage profile
go tool cover -html=cover.out
View coverage report in browser
func BenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { add(1,2) } }
Define a benchmark function
go test -bench=. ./...
Run benchmarks
func ExampleAdd() { fmt.Println(add(1, 2)) // Output: 3 }
Example test with expected output

Common Standard Library

CommandDescription
fmt.Println(a, b)
Print values separated by spaces with newline
fmt.Printf("%v\n", x)
Print with default format
fmt.Fprintf(w, "...")
Write formatted string to an io.Writer
fmt.Scanf("%d", &x)
Read formatted input from stdin
os.Args
Command-line arguments ([]string)
os.Getenv("HOME")
Get an environment variable
os.Setenv("KEY", "val")
Set an environment variable
os.Exit(1)
Exit the program with a status code
os.Open("file.txt")
Open a file for reading
os.Create("file.txt")
Create or truncate a file
os.ReadFile("file.txt")
Read entire file into []byte (Go 1.16+)
os.WriteFile("f.txt", data, 0644)
Write []byte to file (Go 1.16+)
os.MkdirAll("a/b/c", 0755)
Create directories recursively
io.ReadAll(r)
Read all bytes from an io.Reader
io.Copy(dst, src)
Copy from Reader to Writer
strings.Contains(s, sub)
Check if string contains substring
strings.HasPrefix(s, prefix)
Check if string starts with prefix
strings.Split(s, ",")
Split string by separator
strings.Join(parts, ",")
Join string slice with separator
strings.ReplaceAll(s, old, new)
Replace all occurrences in string
strings.TrimSpace(s)
Remove leading/trailing whitespace
strconv.Atoi("42")
Parse string to int
strconv.Itoa(42)
Convert int to string
strconv.ParseFloat("3.14", 64)
Parse string to float64
json.Marshal(v)
Encode a value to JSON []byte
json.Unmarshal(data, &v)
Decode JSON []byte into a value
json.NewEncoder(w).Encode(v)
Stream-encode JSON to a Writer
json.NewDecoder(r).Decode(&v)
Stream-decode JSON from a Reader
http.ListenAndServe(":8080", nil)
Start an HTTP server
http.HandleFunc("/", handler)
Register an HTTP handler function
http.Get(url)
Make an HTTP GET request
resp, err := http.Post(url, contentType, body)
Make an HTTP POST request
time.Now()
Get current time
time.Sleep(2 * time.Second)
Sleep for a duration
time.Since(start)
Duration since a time (for elapsed time)
time.NewTicker(1 * time.Second)
Create a ticker that fires periodically
sort.Ints(s)
Sort a slice of ints in place
sort.Strings(s)
Sort a slice of strings in place
sort.Slice(s, func(i, j int) bool { ... })
Sort a slice with custom comparator
regexp.MatchString(pattern, s)
Check if string matches regex
re := regexp.MustCompile(pattern)
Compile regex (panics on error)
log.Println("message")
Log with timestamp
log.SetFlags(log.LstdFlags | log.Lshortfile)
Configure log output format

More Guides

🌿
Git Commands
Complete Git command reference — from basics to advanced workflows. Searchable, with examples.
📝
Vim Commands
Complete Vim/Vi command reference — modes, motions, editing, search, and advanced features.
🐳
Docker Commands
Complete Docker & Docker Compose command reference — containers, images, volumes, networks, and orchestration.
🔤
Regex Reference
Complete regular expression reference — syntax, patterns, quantifiers, groups, lookaheads, and common recipes.
🐧
Linux Commands
Complete Linux/Bash command reference — file management, text processing, networking, system admin, and shell scripting.
☸️
Kubernetes Commands
Complete Kubernetes & kubectl command reference — pods, deployments, services, configmaps, and cluster management.
🐍
Python Reference
Complete Python reference — syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
🗃️
SQL Reference
Complete SQL reference — queries, joins, aggregation, subqueries, indexes, and database management.
🌐
Nginx Reference
Complete Nginx configuration reference — server blocks, locations, proxying, SSL, load balancing, and caching.
🔐
SSH Commands
Complete SSH reference — connections, key management, tunneling, config, SCP/SFTP, and security hardening.
👷
Jenkins Reference
Complete Jenkins reference — pipeline syntax, Jenkinsfile, plugins, CLI, agents, and CI/CD patterns.
📨
HTTP Headers Reference
Complete HTTP headers reference — request headers, response headers, caching, security, CORS, and content negotiation. Searchable, with examples.
🐘
PostgreSQL Reference
Comprehensive PostgreSQL reference — from connection basics to advanced features like JSONB, full-text search, window functions, and performance tuning.
Async Patterns Reference
Multi-language async/concurrency patterns — JavaScript, Python, Go, Rust, Java, and universal concurrency patterns.
📡
Protobuf & gRPC Reference
Comprehensive reference for Protocol Buffers (proto3) and gRPC — message definitions, services, streaming, and common patterns.
📚
JS Array Methods
Complete JavaScript Array methods reference — creating, searching, transforming, sorting, iterating, and common patterns. Searchable, with examples.
🌊
Tailwind CSS Reference
Complete Tailwind CSS reference — layout, spacing, typography, colors, responsive design, states, and common patterns. Searchable, with examples.
GraphQL Reference
Complete GraphQL reference — schema definition, types, queries, mutations, directives, fragments, and common patterns. Searchable, with examples.
💻
VS Code Shortcuts
Complete VS Code keyboard shortcuts — editing, navigation, search, multi-cursor, terminal, debug, and more. Searchable, with Cmd/Ctrl notation.
🔲
CSS Grid Reference
Complete CSS Grid reference — container properties, item placement, grid functions, and common layout patterns. Searchable, with examples.
📦
CSS Flexbox Reference
Complete CSS Flexbox reference — container properties, item properties, and common layout patterns. Searchable, with examples.
⚛️
React Hooks Reference
Complete React Hooks reference — useState, useEffect, useContext, custom hooks, and common patterns. Searchable, with examples.
🔷
TypeScript Reference
Complete TypeScript reference — types, interfaces, generics, utility types, and advanced patterns. Searchable, with examples.
☁️
AWS CLI Reference
Complete AWS CLI reference — EC2, S3, IAM, Lambda, ECS, RDS, CloudFormation, and common operations.
💠
PowerShell Reference
Complete PowerShell reference — cmdlets, pipelines, scripting, file operations, remote management, and Active Directory.
💾
Redis Commands
Complete Redis command reference — strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and server management.
🏗️
Terraform Commands
Complete Terraform reference — init, plan, apply, state management, modules, workspaces, and HCL syntax.
⚙️
Ansible Commands
Complete Ansible reference — playbooks, modules, inventory, roles, vault, and ad-hoc commands.
🟨
JavaScript
Complete JavaScript reference — variables, types, operators, strings, arrays, objects, functions, async, DOM, ES6+, and more.
🎨
CSS
Complete CSS reference — selectors, box model, positioning, typography, animations, media queries, custom properties, and more.
📄
HTML
Complete HTML reference — document structure, text content, forms, media, semantic elements, accessibility, and more.
Java
Complete Java reference — data types, strings, collections, OOP, interfaces, exceptions, file I/O, streams, lambdas, and more.
💻
Bash
Complete Bash reference — variables, strings, arrays, conditionals, loops, functions, file tests, I/O redirection, process management, and more.
🦀
Rust
Comprehensive Rust language cheat sheet covering ownership, traits, pattern matching, concurrency, and more.
📝
Markdown
Complete Markdown syntax reference for headings, formatting, links, tables, code blocks, and extensions.
📋
YAML
YAML syntax reference covering scalars, collections, anchors, multi-line strings, and common patterns.
🌐
Curl
Curl command-line reference for HTTP requests, authentication, file transfers, debugging, and common API patterns.
Cron
Cron scheduling reference covering syntax, field values, crontab management, and common schedule patterns.
🖥️
Tmux
Terminal multiplexer for managing multiple sessions, windows, and panes from a single terminal.
🔧
Awk
Powerful text processing language for pattern scanning, data extraction, and report generation.
✂️
Sed
Stream editor for filtering and transforming text, line by line.
🔍
Find
Search for files and directories in a directory hierarchy with powerful filtering options.
🔎
Grep
Search text using patterns. Filter lines from files, command output, or streams with regular expressions.
🐘
PHP
Complete PHP cheat sheet covering syntax, OOP, arrays, PDO, and modern PHP 8.x features.
⚙️
C
Complete C programming cheat sheet covering syntax, pointers, memory management, and standard library.
🔷
C++
Complete C++ cheat sheet covering STL containers, OOP, templates, smart pointers, and modern C++ features.
🐬
MySQL
Complete MySQL cheat sheet covering queries, joins, indexes, transactions, and administration.
💅
Sass
Complete Sass/SCSS cheat sheet covering variables, mixins, functions, nesting, and modern module system.
🔐
Chmod
Linux file permission commands and patterns for chmod.
🔢
NumPy
Essential NumPy commands for array manipulation and numerical computing in Python.
🐼
Pandas
Pandas cheat sheet for data manipulation, analysis, and transformation in Python.
🎯
Dart
Dart language cheat sheet covering syntax, types, OOP, null safety, and async patterns.
🔺
Laravel
Laravel PHP framework cheat sheet for routing, Eloquent, Blade, Artisan, and more.
🟩
Node.js
Comprehensive Node.js runtime reference covering modules, file system, HTTP, streams, and more.
Next.js
Next.js App Router reference covering routing, data fetching, server components, and deployment.
🍃
MongoDB
MongoDB reference covering CRUD operations, aggregation, indexes, and administration.
🔥
Firebase
Firebase reference covering Authentication, Firestore, Realtime Database, Cloud Functions, and Hosting.
🐳
Docker Compose
Docker Compose reference covering CLI commands, service configuration, networking, volumes, and more.
💲
jQuery
Quick reference for jQuery selectors, DOM manipulation, events, AJAX, and more.
📐
LaTeX
Quick reference for LaTeX document structure, math mode, formatting, and common packages.
🎯
XPath
Quick reference for XPath expressions, axes, predicates, and functions for XML/HTML querying.
Emmet
Quick reference for Emmet abbreviations for lightning-fast HTML and CSS coding.
📦
TOML
Quick reference for TOML configuration file syntax, types, tables, and common patterns.
💎
Prisma
Complete Prisma ORM cheat sheet — schema, queries, migrations, and CLI.
🤖
GitHub Actions
Complete GitHub Actions cheat sheet — workflows, triggers, jobs, and CI/CD patterns.
📦
npm
Complete npm cheat sheet — package management, scripts, publishing, and configuration.
Supabase
Complete Supabase cheat sheet — auth, database, realtime, storage, and edge functions.
🪶
Apache
Complete Apache HTTP Server cheat sheet — virtual hosts, modules, rewrite rules, and SSL.
📡
HTTP Status Codes
Complete reference of all standard HTTP response status codes with descriptions and use cases.
🔤
ASCII Table
Complete ASCII character reference with decimal, hexadecimal, and character values.
🔧
Chrome DevTools
Essential Chrome DevTools shortcuts, commands, and workflows for web developers.
💧
Drizzle ORM
Complete Drizzle ORM reference for schema definition, queries, relations, migrations, and common patterns.
Vercel CLI
Complete Vercel CLI reference for deployment, project management, domains, environment variables, and configuration.
🔄
PM2
Production process manager for Node.js applications with built-in load balancer, monitoring, and zero-downtime reloads.
📺
Screen
GNU Screen terminal multiplexer for persistent sessions, window management, and remote work.
📦
Webpack
Module bundler for JavaScript applications — loaders, plugins, code splitting, optimization, and dev server.
Vite
Next-generation frontend build tool with instant HMR, native ES modules, and optimized production builds via Rollup.

📖 Free, searchable command reference. Bookmark this page for quick access.