-
- 1. Basic Syntax
- 2. Comments
- 3. Declarations & Identifiers
- 4. Types & Type Conversions
- 5. Constants & iota
- 6. Control Flow
- 7. Functions
- 8. Defer, Panic, and Recover
- 9. Structs & Methods
- 10. Pointers
- 11. Interfaces
- 12. Arrays & Slices
- 13. Maps
- 14. Generics (Go 1.18+)
- 15. Error Handling (Basic Pattern)
- 16. Concurrency Primitives
- 17. Built-in Functions
-
- Package Overview
- 1. I/O and File System
- 2. Strings and Byte Slices
- 3. Networking and HTTP
- 4. Data Encoding
- 5. Concurrency and Synchronization
- 6. Time
- 7. Math and Random
- 8. Logging
- 9. Errors
- 10. Testing
- 11. Templates
- 12. Command-Line Flags
- 13. Reflection
- 14. Runtime Control and Diagnostics
- 15. Slices, Maps, and Sorting
- 16. Cryptography (Selected Essentials)
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.
// single-line comment
/*
multi-line comment
*/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 declaredBasic 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 complex128Type 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 aliasconst 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
)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
}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 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:
// ...
}// 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
}
}// 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
}// 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 promotedvar 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// 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 intvar 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// 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// 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 {
// ...
}// 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
}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 resultgo someFunc(args) // start new goroutine
go func() {
// anonymous goroutine
}()// 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
}(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 |
| 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 |
- File operations:
os.Open(name) (*File, error),os.Create(name) (*File, error),os.OpenFile(name, flag, perm)(flags likeos.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
- Core interfaces:
io.Reader(methodRead(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.MultiWriterio.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)
- 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) boolfs.WalkDir(fsys FS, root string, fn WalkDirFunc) errorfs.Glob(fsys FS, pattern string) (matches []string, err error)
- Scanner:
bufio.NewScanner(io.Reader)– line-by-line scanning (default); useSplitfor custom (e.g.,bufio.ScanWords,bufio.ScanBytes). Methods:Scan() bool,Text() string,Err() error. - Reader:
bufio.NewReader(rd io.Reader)with methodsReadString(delim byte),ReadBytes(delim byte),ReadLine(),Peek(n int). - Writer:
bufio.NewWriter(w io.Writer)withWrite,WriteString,Flush.bufio.NewWriterSize(w, size)for custom buffer size.
- 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; preferfilepath.WalkDir(Go 1.16+) withfs.DirEntryfor efficiency. - Matching:
filepath.Glob(pattern) ([]string, error) - Clean and Abs:
filepath.Clean(path),filepath.Abs(path)
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.FSThe embed.FS implements fs.FS, so it can be used with http.FileServer, fs.ReadFile, etc.
- 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==)
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 withWrite,Read,String,Bytes, useful for building and reading byte sequences. - Clone:
bytes.Clone(b) []byte(since Go 1.20) – deep copy.
- String ↔ Integer:
strconv.Atoi(s string) (int, error),strconv.Itoa(i int) stringstrconv.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.IsDigit(r),unicode.IsLetter(r),unicode.IsSpace(r),unicode.IsUpper(r),unicode.IsLower(r)unicode.ToUpper,unicode.ToLowerunicode.UTF8sub‑package for more specific UTF‑8 checks.
- 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
- Dial/Listen:
net.Dial(network, address)(e.g., "tcp", "golang.org:80") →net.Connnet.Listen(network, address)→net.Listener
- Connection:
Conninterface (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.IPmethods (To4,String,Equal)
- Client (Quick):
http.Get(url)→*http.Response, errorhttp.Post(url, contentType, body),http.PostForm(url, data url.Values)
- Client (Custom):
http.ClientwithTransport,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 withio.ReadAll.- Important: Always close the response body (
defer res.Body.Close())
- Important: Always close the response body (
- Server:
http.HandleFunc(pattern, handlerFunc)– register a handler.http.ListenAndServe(addr, handler)– start server;niluses default mux.- Custom
http.Serverwith fields likeAddr,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.Handlerviahttp.HandlerFuncadapter. - ServeMux enhancements: Since Go 1.22, pattern matching supports
GET,POST, path parameters with{name},http.NewServeMux().
url.Parse(rawURL) (*URL, error)– parse and decompose URL (Scheme, Host, Path, RawQuery, etc.)url.Query() Values– returnsurl.Valuesmap.Values.Get(key),Values.Add(key, value),Values.Encode()→ query string.
- 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)withEncode(v),json.NewDecoder(r io.Reader)withDecode(v). - Struct tags:
json:"fieldname,omitempty,string", can hide fields withjson:"-" - Raw messages:
json.RawMessageto delay decoding. - Decoder:
DisallowUnknownFields(),UseNumber()(to decode numbers asjson.Numberinstead of float64).
xml.Marshal,xml.Unmarshal- Struct tags:
xml:"name,attr,omitempty"andxml:",chardata" xml.Decoder(streaming) withToken()for large files.
- Reader:
csv.NewReader(r io.Reader), options likeComma,LazyQuotes.Read() (record []string, err error),ReadAll() (records [][]string, err error) - Writer:
csv.NewWriter(w io.Writer),Write(record),Flush,Commasetting.
base64.StdEncoding.EncodeToString(src),DecodeString(s)base64.URLEncodingfor URL-safe variant.
- Mutex:
sync.MutexwithLock()/Unlock().sync.RWMutexfor multiple readers (RLock/RUnlock). - WaitGroup:
var wg sync.WaitGroup.wg.Add(delta),wg.Done(),wg.Wait(). - Once:
sync.Once–Do(f func())ensures f runs exactly once. - Map:
sync.Map– concurrent map withLoad,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.
- 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 likeAdd,Load,Store,CompareAndSwap. Prefer these over raw functions.
- Creation:
context.Background()– root context for main, init, etc.context.TODO()– placeholder.context.WithCancel(parent) (ctx, cancel)– create cancellable context; callcancel()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, notstring).
- Usage:
ctx.Done() <-chan struct{}– closed when cancelled/timed out.ctx.Err()– returns reason (context.Canceledorcontext.DeadlineExceeded).ctx.Value(key) interface{}– retrieve value.
- Rule: Pass context as first argument, typically named
ctx.
- 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 channelCthat fires repeatedly.ticker.Stop(). - Timer:
time.NewTimer(d)– fires once; stop withtimer.Stop(), reset withtimer.Reset(d).time.After(d)returns channel (for simple cases). - Location:
time.LoadLocation(name),time.FixedZone,t.In(loc).
- 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+, otherwisemath.Max/Minfor floats).
- 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.ChaCha8as crypto-like random for shuffle. Usecrypto/randfor security-sensitive randomness.
log.Println(v ...),log.Printf(format, v ...),log.Fatal(v ...),log.Fatalf,log.Paniclog.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.
- Logger:
slog.New(slog.NewJSONHandler(w, nil)),slog.NewTextHandler - Levels:
slog.Debug,slog.Info,slog.Warn,slog.Error. Useslog.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}
- Creation:
errors.New(text string) error,fmt.Errorf("...: %w", err)wraps an error. - Inspection:
errors.Is(err, target) bool– checks iferristarget(following the chain).errors.As(err, target interface{}) bool– extracts the first error in chain that matchestargettype and setstarget.
- Unwrap:
errors.Unwrap(err) error– returns next wrapped error. - New helpers (Go 1.20+):
errors.Join(errs ...error)– combines multiple errors into one.
- Test function:
func TestXxx(t *testing.T)(must start withTest). 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-vflag.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 loopfor i := 0; i < b.N; i++ { ... }.b.ReportAllocs(). - Fuzzing (Go 1.18+):
func FuzzXxx(f *testing.F). Add seeds withf.Add(...), thenf.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().
fstest.TestFS(fsys fs.FS, expected ...string)– verifies a file system contains the expected files.
- 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.FuncMapto add custom functions. - Template nesting:
{{template "name"}}or{{template "name" .}}
- Identical API to
text/templatebut contextually escapes output to prevent XSS. Always use it for HTML generation.
- 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()andflag.Arg(i). - Custom flags: implement
flag.Valueinterface.
- 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.
- 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)– populateruntime.MemStatswith 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.
debug.PrintStack()– print stack trace.debug.SetMaxStack(bytes)– set max goroutine stack.debug.FreeOSMemory()– force scavenge memory to OS.
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.Reverseslices.Sort(s),slices.SortFunc(s, cmp),slices.BinarySearch(s, target)(slice must be sorted).
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 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.
sha256.Sum256(data []byte) [32]byte,sha256.New()(returnshash.Hash)- Hash interface:
io.Writerfor feeding data,Sum(b []byte) []byte,Reset()
md5.Sum(data) [16]byte,md5.New()
rand.Read(b []byte) (n int, err error)– fill slice with random bytes.rand.Int(rand io.Reader, max *big.Int)– random integer.
hash.New()pattern withio.WriteString(h, "data"), thenh.Sum(nil)to finalize.
The go command is the central tool for managing Go source code, covering the entire development lifecycle from building and testing to dependency management.
| 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. |
| 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. |
go tool: Run a specific Go tool. Usego toolto 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
GOEXPERIMENTenvironment variable to enable experimental features from the command line. For example,GOEXPERIMENT=loopvar go test ./....
The go mod command is the cornerstone of modern Go dependency management.
| 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. |
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)
These tools are separate from the go command but are essential for a professional development workflow.
- 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 .
- A superset of
gofmtthat automatically manages import lines. - Install:
go install golang.org/x/tools/cmd/goimports@latest - Use as a replacement for
gofmt:goimports -w main.go
- Examines source code for common suspicious constructs (e.g., bad
Printfcalls). - 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 exceptprintf) - 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.
- 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
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. |
| 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. |
- Install Go: Download from go.dev and follow the instructions.
- Add to PATH: Ensure
$GOPATH/binis in your system'sPATHenvironment variable to easily run installed tools.