📖 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
BasicsTypesControl FlowFunctionsStructs & MethodsInterfacesError HandlingGoroutines & ChannelsPackages & ModulesTestingCommon Standard Library
Basics
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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) inte.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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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
| Command | Description |
|---|---|
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 |
📖 Free, searchable command reference. Bookmark this page for quick access.