Go Documentation
Concise, example-driven Go reference. Read the concept, see the code, then practice it in a Coddy journey.
Start a guided Go journeyGetting Started
- What Is Go?Go (often called Golang) is a statically typed, compiled language designed at Google for building fast, reliable servers and tools. This page covers what it is, what it is used for, and where it falls short.
- Install GoHow to download and install Go on Windows, macOS and Linux, check the install with go version, understand GOPATH, and fix the "go: command not found" error.
- Hello WorldThe Go hello world program line by line: package main, the import block, func main, and fmt.Println, plus how to run it and the compile errors beginners hit first.
- go run and go buildWhat go run, go build and go install each do, how Go names the binary, how to cross-compile with GOOS and GOARCH, and the go fmt and go vet checks to run before you commit.
- Go ModulesHow Go modules work: creating one with go mod init, choosing a module path, adding dependencies with go get, cleaning up with go mod tidy, what go.sum is for, and replace for local development.
- Packages and ImportsHow Go packages work: the package clause, importing standard and module packages, exported vs unexported names, splitting a package across files, internal packages, import aliases, blank imports, and the "undefined" error from go run main.go.
Basics
- VariablesHow to declare variables in Go with var and the := short form, what zero values are, multiple assignment, and the shadowing and unused-variable errors that catch new Go programmers.
- ConstantsHow const works in Go: declaring constants, the difference between typed and untyped constants, constant expressions with arbitrary precision, and why Go has no constant slices, maps or structs.
- Enums and iotaGo has no enum keyword. This page shows the idiomatic replacement: a named type plus a const block with iota, and how to add String(), validation, parsing, bit flags and JSON support.
- Data TypesGo's built-in types: integer sizes and ranges, float32 and float64, bool, string, byte and rune, complex numbers, zero values, and how to print a value's type with %T.
- Type ConversionHow to convert between types in Go: int to string and string to int with strconv, floats to ints, numeric conversions with T(v), bytes and runes, the string(65) trap, and handling conversion errors.
- StringsWorking with strings in Go: the strings package (Split, Join, Contains, Replace, Fields, TrimSpace, ToUpper), building strings efficiently with strings.Builder, multiline raw strings, immutability, and why len counts bytes.
- Runes and BytesWhat rune and byte mean in Go, how strings store UTF-8, why len counts bytes, how range decodes runes, converting between string, []byte and []rune, and working with the bytes package.
- fmt.Printf and SprintfHow Go's fmt package prints and formats values: Println vs Printf vs Sprintf vs Errorf, the full table of format verbs (%v, %+v, %d, %s, %q, %f, %T, %w and more), width, precision and padding.
Control Flow
- if / elseHow if, else if and else work in Go: no parentheses, required braces, the if statement with an init clause and its scope, the if err != nil idiom, and early returns instead of deep nesting.
- for LoopGo has one loop keyword, for, and it covers everything: the three-clause counter loop, the condition-only while loop, the infinite loop, and range over slices, maps, strings, channels, integers and functions. Plus labeled break and continue and the Go 1.22 loop variable change.
- while LoopGo has no while keyword. A for loop with only a condition is Go's while loop, for with no condition is an infinite loop, and a do-while is an infinite loop with the check at the end.
- range LoopsWhat for range yields for slices, arrays, strings, maps, channels, integers and iterator functions, why the value variable is a copy, what happens when you modify a slice or map while ranging, and range over func in Go 1.23.
- switch StatementHow switch works in Go: cases do not fall through by default, one case can list several values, switch with no condition replaces if/else chains, switch with an init statement, the fallthrough keyword, and a short look at type switches.
- Ternary OperatorGo has no ternary operator (cond ? a : b). This page explains why, shows the idiomatic if/else replacement, cmp.Or for defaults, and a generic helper function along with the trap that makes it different from a real ternary.
Functions
- FunctionsHow to declare and call functions in Go: parameters, shared parameter types, return values, pass by value, and functions as values you can store and pass around.
- Multiple Return ValuesGo functions can return several values. This page covers the syntax, the (value, error) convention, the comma-ok idiom, named results, naked returns and the blank identifier.
- Variadic FunctionsA variadic Go function accepts any number of trailing arguments of one type. Learn the ...T syntax, how to pass a slice with s..., the aliasing gotcha, and how fmt.Println uses ...any.
- ClosuresAnonymous functions in Go can capture variables from the scope around them. That makes closures: counters, generators, middleware, and callbacks that keep their own state.
- defer Statementdefer schedules a call to run when the surrounding function returns. Learn LIFO order, when arguments are evaluated, closing files and unlocking mutexes, defer in loops, and changing named results.
- MethodsA method is a function with a receiver. Learn how to declare methods, when to use a value or a pointer receiver, method sets and interfaces, and methods on non-struct types.
Collections
- ArraysA Go array has a fixed length that is part of its type, and it is copied on assignment. Learn how to declare, iterate, compare and pass arrays, and why most Go code uses slices instead.
- SlicesSlices are Go's everyday list type. Learn make, append and growth, len vs cap, how slicing shares the backing array (and the bug that causes), copy, the slices package, 2D slices, and nil vs empty.
- MapsGo maps store key-value pairs with fast lookup. Learn how to create them, check if a key exists with comma-ok, delete, iterate (in random order), sort keys, store structs, and avoid the nil map and concurrent write panics.
- SetsGo has no built-in set type. The standard idiom is a map with empty struct values. Learn add, has and remove, union, intersection and difference, and how to write a small generic Set.
- SortingSort slices in Go with slices.Sort and slices.SortFunc, sort structs by one or several fields with cmp.Compare, keep equal elements in order with a stable sort, and read older sort.Slice code.
Structs, Interfaces and Generics
- StructsStructs group named fields into one type. Learn how to define and initialize them, zero values, pointers to structs, anonymous structs, comparison, struct tags, and the NewX constructor convention.
- PointersA pointer holds the address of a value. Learn & and *, new, pointers to structs, why you can safely return a pointer to a local variable, when to use pointers, and the nil pointer dereference panic.
- InterfacesGo interfaces are satisfied implicitly: any type with the right methods implements them. Learn small interfaces like io.Reader and fmt.Stringer, the empty interface any, the nil interface gotcha, and accept interfaces, return structs.
- Struct EmbeddingEmbedding puts one type inside another without a field name, so its fields and methods are promoted to the outer type. Learn how promotion works, embedding interfaces, name conflicts, and why embedding is not inheritance.
- Type AssertionsA type assertion gets the concrete value out of an interface. Learn x.(T), the comma-ok form that never panics, asserting to another interface, type switches, and errors.As for wrapped errors.
- GenericsGenerics (Go 1.18+) let one function or type work with many types while staying type-safe. Learn type parameters, the any, comparable and cmp.Ordered constraints, custom constraints with ~, generic types, and when not to use them.
Errors
- Error HandlingGo handles errors as ordinary values returned from functions. Learn the error interface, if err != nil, errors.New and fmt.Errorf, returning errors with context, checking them with errors.Is and errors.As, and handling each error once.
- Custom ErrorsDefine sentinel errors and custom error types, wrap errors with %w, check them with errors.Is and errors.As, combine several with errors.Join, and write Unwrap and Is methods when you need them.
- panic and recoverA panic stops normal execution and unwinds the stack, running deferred calls. Learn what causes panics, how recover in a deferred function stops one, the runtime error messages you will see, and when panicking is the right call.
Concurrency
- GoroutinesHow to run functions concurrently with the go keyword, wait for them to finish, get results back, and avoid the data races, leaks and crashes that goroutines make easy.
- ChannelsHow Go channels pass values between goroutines: unbuffered and buffered channels, closing and ranging, direction types, the deadlock error, and a pipeline built from them.
- select StatementHow select waits on several channel operations at once: picking among ready cases, non-blocking sends and receives with default, timeouts with time.After, and stopping loops with a quit channel or context.
- WaitGroupHow sync.WaitGroup waits for a set of goroutines to finish: the Add, Done and Wait rules, why it must be passed by pointer, collecting results and errors, and a worker pool built on it.
- MutexHow to protect shared state between goroutines with sync.Mutex and sync.RWMutex, when sync/atomic is enough, how sync.Once runs setup exactly once, and the locking mistakes that cause deadlocks.
- context PackageHow context.Context carries cancellation, deadlines and request-scoped values through a Go program: Background, WithCancel, WithTimeout, WithValue, ctx.Done in select, and context in HTTP servers and clients.
Standard Library
- time PackageHow to work with dates and times in Go: time.Now and time.Sleep, Duration arithmetic, the 2006-01-02 15:04:05 reference layout for Format and Parse, time zones, Unix timestamps, and timers and tickers.
- JSONHow to encode and decode JSON in Go with encoding/json: Marshal and Unmarshal, struct tags like omitempty and omitzero, pretty printing, decoding into map[string]any, rejecting unknown fields, and streaming with Decoder.
- Reading and Writing FilesHow to read and write files in Go: os.ReadFile and os.WriteFile, reading line by line with bufio.Scanner, appending with os.OpenFile, checking whether a file exists, and working with directories.
- HTTP ServerHow to build a web server with Go's standard net/http package: handlers, ServeMux routing with methods and path wildcards (Go 1.22), JSON responses, status codes, middleware, timeouts and graceful shutdown.
- HTTP ClientHow to make HTTP requests in Go with net/http: http.Get, reading and closing the body, checking status codes, http.Client timeouts, requests with context and headers, query parameters, and POSTing JSON.
- Command-Line ArgumentsHow a Go program reads its command line: os.Args, the flag package for typed options, subcommands with FlagSet, environment variables with os.Getenv and os.LookupEnv, and exit codes with os.Exit.
- Regular ExpressionsHow to use regular expressions in Go with the regexp package: MustCompile, MatchString, FindString and FindAllString, capture groups and named groups, ReplaceAllString, and the RE2 syntax limits such as no lookbehind.
- LoggingHow to log in Go: the classic log package with its flags and log.Fatal, and log/slog (Go 1.21) for structured logs with levels, key-value attributes, text and JSON handlers, and loggers that carry context with With.
Testing and Project Layout
- TestingHow to test Go code with the standard testing package and go test: _test.go files, TestXxx functions, t.Errorf versus t.Fatalf, table-driven tests with t.Run, helpers and temp dirs, coverage, benchmarks with b.Loop, and example tests.
- Project StructureHow to lay out a Go project: start flat, split into packages when there is a reason, use cmd/ for multiple binaries and internal/ for code no one else may import, name packages well, and keep tests next to the code.