Go Roadmap
Go is a compiled language made for network services and command line tools. It is small enough to learn in weeks, and large systems such as container platforms and cloud tooling are written in it. Companies that run backends, platform teams and infrastructure products hire for it regularly.
This roadmap takes you from installing the toolchain to profiling a production service. Each stage lists topics in the order they are best learned, explains each one, and gives you one exercise. After that come projects, real interview questions with model answers, common mistakes and a readiness checklist.
By the end you should be able to write idiomatic Go, design with small interfaces, use goroutines and channels without leaking them, test and benchmark your code, and explain the trade-offs behind the language's choices.
- Level
- Beginner to advanced
- Time
- 10-14 weeks at about 8 hours a week
- Scope
- 64 topics in 8 stages
- Before you start
- Programming basics in any language: variables, loops, functions; Comfort with a terminal and a text editor; Optional: Git and GitHub Roadmap for the projects
What you will be able to do
- Write idiomatic Go programs using packages, structs, methods and interfaces
- Handle errors the Go way, with wrapping, sentinel values and custom types
- Build concurrent programs with goroutines, channels, select and context, and avoid leaks and races
- Use generics where they help and explain when they do not
- Manage dependencies with modules, and test, benchmark, lint and profile your code
- Build and ship an HTTP or gRPC service backed by a database as a static binary
- Answer common Go interview questions about slices, maps, interfaces and concurrency
The roadmap at a glance
- Stage 1Getting Started with GoBeginner · 1 week · 7 topics
- Stage 2Core Language: Values and Control FlowBeginner · 2 weeks · 9 topics
- Stage 3Data Structures, Methods and PointersBeginner · 2 weeks · 9 topics
- Stage 4Interfaces, Errors and GenericsIntermediate · 2 weeks · 7 topics
- Stage 5ConcurrencyIntermediate · 3 weeks · 7 topics
- Stage 6Standard Library and I/OIntermediate · 2 weeks · 8 topics
- Stage 7Modules, Testing and ToolingIntermediate · 2 weeks · 9 topics
- Stage 8Web Services, Data and ProductionAdvanced · 3 weeks · 8 topics
Stage 1 Getting Started with Go
Goal. Install the toolchain, run and build a program, and explain how Go code is organised into packages.
Introduction to Go Core
Go is a statically typed, compiled language with a small feature set and a fast compiler. A Go program builds to one native executable with no separate runtime to install, and the language has garbage collection, built-in concurrency and a large standard library.
The design aim is that a team can read each other's code quickly. There is one formatting style, few ways to do the same thing and no inheritance or operator overloading. That plainness is the main thing to understand: when you meet a design choice in Go, the answer to "why is it like this?" is usually "to keep code boring and predictable".
Go is used for network services, command line tools, cloud infrastructure and DevOps software.
Practice. Write five sentences explaining what makes Go different from the language you know best.
Why use Go Core
Teams choose Go for a few practical reasons:
- Fast builds and quick feedback while developing.
- Cheap concurrency through goroutines, which suits servers handling many connections.
- A single static binary that is easy to ship in a small container image.
- A standard library that covers HTTP, JSON, testing and cryptography without third-party code.
- Tooling (formatter, test runner, profiler) that ships with the language.
Go is a weaker fit for heavy numeric work, rich desktop interfaces or code that needs precise control over memory layout. In an interview, be ready to name those trade-offs as well as the strengths. See Rust Roadmap and Modern C++ Roadmap for languages that sit at the other end of the control scale, and Docker Roadmap and Kubernetes Roadmap for tools written in Go.
Practice. List two services you would build in Go and one you would not, with a reason for each.
History of Go Optional
Go was designed at Google by Robert Griesemer, Rob Pike and Ken Thompson, who were frustrated by slow C++ builds and the complexity of large codebases. It was announced publicly in 2009, and version 1.0 followed in 2012 with a promise that programs written for Go 1 would keep compiling. That compatibility promise still holds and explains why old Go code usually works unchanged.
Notable later steps include modules replacing the old GOPATH workflow, and generics arriving in Go 1.18. Newer releases added the log/slog package, improved loop variable semantics and range-over-function iterators. Check the official release notes for details instead of memorising version numbers.
Practice. Read the release notes of the latest Go version and note two changes that affect everyday code.
Setting up the Environment Core
Install Go from the official download for your system or a package manager, then check it with go version. Modern Go needs no GOPATH setup for your own projects: code lives in any folder that contains a go.mod file.
Useful commands for the environment are go env (prints settings such as GOOS, GOARCH and GOPATH) and go env -w to change a setting. Editors such as VS Code with the Go extension, or GoLand, use the language server gopls for completion, navigation and rename.
On first use the toolchain may download the Go version a module asks for, because the go line in go.mod can select a toolchain. Keep this in mind when builds behave differently between machines.
Practice. Install Go, run go version and go env, and open a folder in your editor with gopls working.
Hello World in Go Core
Create a folder, run go mod init example.test/hello, and add main.go:
package main
import "fmt"
func main() {
fmt.Println("Hello, Go")
}Every file starts with a package clause. The main package with a main function is the entry point of an executable. Imports are listed by package path, and unused imports are compile errors, as are unused local variables. That strictness feels odd at first but keeps code clean.
Run it with go run ., or build a binary with go build and execute the file it produces.
Practice. Change the program to read a name from os.Args and greet that person, with a default when none is given.
The go Command Core
The go command is the front door to the toolchain. The ones you will use daily:
go runcompiles and runs a package without keeping the binary.go buildcompiles and writes an executable (or checks that a library compiles).go installbuilds and places the binary in your Go bin folder, which is how many tools are installed.go fmtrewrites files into the standard layout. Run it on save.go vetreports suspicious code such as wrong format verbs.go testruns tests.go docprints documentation, for examplego doc strings.Builder.go cleanremoves build artefacts, andgo clean -cacheempties the build cache.go versionprints the installed version, and works on binaries too.
Learning to read go help output will save time later.
Practice. Use go doc to look up three standard library functions without opening a browser.
Packages and Imports Core
A package is a folder of .go files that share a package name, and it is the unit of reuse. Names that start with a capital letter are exported (visible to other packages); lowercase names are private to the package. There is no public keyword.
Package import rules to remember: import paths are module path plus folder; import cycles are forbidden; a blank import such as import _ "image/png" runs a package's init function for side effects only; an alias such as import str "strings" renames a package locally. Folders called internal can only be imported from code inside the parent tree, which is how you hide implementation details. Keep package names short, lowercase and without underscores.
Practice. Split a small program into two packages, export one function, and make a helper private.
Stage 2 Core Language: Values and Control Flow
Goal. Write small programs using variables, the basic types, strings, control flow and functions.
Variables & Constants, and Zero Values Core
Declare a variable with var x int, with an initial value var x = 5, or inside a function with the short form x := 5. The short form needs at least one new name on the left and works only inside functions, so package-level code uses var.
Every variable has a zero value when you do not set one: 0 for numbers, false for booleans, "" for strings and nil for pointers, slices, maps, channels, functions and interfaces. Designing types so that the zero value is useful (a sync.Mutex or a bytes.Buffer works straight away) is a Go habit that interviewers like to hear.
Constants use const, are evaluated at compile time and can be untyped, which lets const Big = 1 << 40 be used with several numeric types.
Practice. Declare variables of five types without values and print them with %v and %T.
const and iota Recommended
Inside a const block, iota starts at zero and increases by one for each line. Go has no enum keyword, so this is how enumerations are written:
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
)Later lines repeat the previous expression, so KB = 1 << (10 * (iota + 1)) can build a series of sizes. Give the constants a named type and add a String() method so values print as words. Beware that nothing stops someone from converting any integer to that type, so validate when values come from outside.
Practice. Define an enum for log levels with a String method and print each level.
var vs :=, Scope and Shadowing Core
Use var when you want the zero value, need a package-level variable, or want to state the type explicitly. Use := for most local declarations.
Scope in Go is lexical: a name belongs to the nearest enclosing block, and each if, for and switch creates its own block. Shadowing means declaring a new variable with the same name in an inner block. It is legal and causes a classic bug:
var err error
if cond {
result, err := compute() // new err, hides the outer one
_ = result
}Here the outer err stays nil. Use = instead of := when you mean to assign, and run go vet or a linter with a shadow check.
Practice. Reproduce the shadowed err bug in a small program, then fix it two different ways.
Data Types: Integers, Floats, Complex and Booleans Core
Integers come in signed (int8 to int64, and int) and unsigned (uint8 to uint64, uint, uintptr) forms. int is 32 or 64 bits depending on the platform; use it unless you have a reason. byte is an alias of uint8. Integer overflow wraps silently, and division of integers truncates toward zero.
Floating points are float32 and float64; prefer float64, and never compare floats for equality or store money in them. Use integer cents or a decimal library. Complex numbers (complex64, complex128) exist but are rare outside numeric work.
The bool type is true or false only. Go does not treat numbers or pointers as truthy, so if x { needs an actual boolean.
Practice. Show integer overflow of an int8 and the classic 0.1 + 0.2 float result in a short program.
Type Conversion and Type Inference Core
Go never converts between numeric types implicitly. You write float64(count) or int(price), even from int32 to int64. Converting a float to an integer drops the fraction, and converting an integer to a string (string(65)) gives the character with that code point, not the digits; use strconv.Itoa or fmt.Sprint for digits. Parse text with strconv.Atoi and strconv.ParseFloat, and always check the error.
Type inference means the compiler works out the type of a variable from the right-hand side: x := 3.5 is a float64, n := 7 is an int. Untyped constants adopt the type they are assigned to. Generic calls infer type arguments from the function arguments in the same spirit.
Practice. Read a number from the command line with strconv, handle bad input, and print the value converted to float64.
Strings, Runes and Literals Core
A Go string is an immutable sequence of bytes, usually holding UTF-8 text. len(s) counts bytes, not characters. A rune is an int32 holding one Unicode code point.
Interpreted string literals use double quotes and process escapes like \n. Raw string literals use backticks, keep everything as written and may span lines, which suits regular expressions and embedded JSON.
Iterating strings with for i, r := range s decodes runes; indexing s[i] gives bytes. To change characters, convert to []rune, edit, and convert back. Building a large string by repeated + is slow, so use strings.Builder. The strings, unicode and utf8 packages cover splitting, trimming, case mapping and counting runes.
Practice. Count the bytes and the runes in a string containing an emoji-free accented word, and reverse it safely.
Conditionals, the for loop and for-range Core
if takes no parentheses and braces are mandatory. It can start with a short statement: if v, err := f(); err != nil { ... }. The scope of v and err covers the whole if and else chain, so most error handling is shaped this way. There is no ternary operator.
switch does not fall through; each case ends on its own, and fallthrough is explicit and rare. A case can hold several values, and a switch without a tag works as a tidy if-else chain.
for is the only loop: for i := 0; i < n; i++, for cond {}, for {} and for i, v := range x. Use break and continue, optionally with labels. goto exists and is discouraged. Since Go 1.22 each iteration has its own loop variable, which removes a common closure bug.
Practice. Write FizzBuzz twice, once with if-else and once with a tagless switch.
Function Basics and Multiple Return Values Core
A function is declared with func name(a int, b string) (int, error). Functions may return several values, and the idiom is a result plus an error at the end. Callers ignore a value with the blank identifier _.
Named return values give the results names and a bare return sends their current values. They help documentation and defer tricks, but long functions with bare returns are hard to read, so use them sparingly.
Variadic functions take ...T, which arrives as a slice, and you pass an existing slice with xs.... Functions are values: you can store them in variables, pass them around and return them. Go passes everything by value, including slices and maps, which are small headers that point at shared data.
Practice. Write a divmod function with two results, and a variadic sum function called with a slice.
Anonymous Functions, Closures and defer Core
An anonymous function has no name and can be called straight away or stored. A closure is one that uses variables from the surrounding function, and it keeps them alive:
func counter() func() int {
n := 0
return func() int { n++; return n }
}Each call of counter() makes an independent n. Closures are the basis of middleware, callbacks and small option functions.
defer schedules a call to run when the surrounding function returns, in last-in first-out order. Arguments are evaluated at the defer statement. Use it for closing files and releasing resources next to where they were acquired. Avoid defer inside long loops, because the calls pile up until the function ends.
Practice. Write a function that returns a closure generating Fibonacci numbers, then wrap file closing with defer.
Stage 3 Data Structures, Methods and Pointers
Goal. Choose between arrays, slices, maps and structs, and use pointers and methods correctly.
Arrays Core
An array has a fixed length that is part of its type: [3]int and [4]int are different types. Arrays are values, so assigning or passing one copies every element. Because of that, plain arrays are uncommon in application code. They show up as keys in maps (arrays are comparable, slices are not), for fixed-size data such as hashes, and as the storage behind slices.
var grid [3][3]int
grid[1][2] = 5
sum := [...]int{1, 2, 3} // length counted by the compiler
Practice. Declare an array of seven days, copy it into a second variable, change one copy and show that the other is unaffected.
Slices Core
A slice is a small header with three fields: a pointer to an array, a length and a capacity. Reslicing s[1:3] creates a new header over the same memory, so writes through one slice can be seen through another. Appending uses s = append(s, x), and you must assign the result because append may move the data.
Slices are not comparable with == (except to nil). A nil slice and an empty slice both have length zero and work with append and range, but they differ when encoded as JSON. Useful standard helpers live in the slices package: slices.Sort, slices.Contains, slices.Index and more.
Practice. Write a function that removes one element from a slice and explain what happens to the original backing array.
Capacity and Growth, and make() Core
make([]int, length, capacity) creates a slice with room to grow. When append exceeds the capacity, the runtime allocates a bigger array (roughly doubling for small slices, growing more slowly for large ones), copies the data and returns a new header. Old references then point at stale memory.
That is the source of two well-known surprises. First, a sub-slice created before the growth no longer shares data with the result. Second, a small slice of a huge array keeps the whole array alive; copy the part you need with copy or slices.Clone to release it.
Preallocate with make([]T, 0, n) when you know the size, because it avoids repeated copying. make is also used for maps and channels, while new(T) returns a pointer to a zeroed value.
Practice. Print len and cap while appending 20 items to a slice and note when the capacity changes.
Array to Slice Conversion and Slice to Array Conversion Recommended
Go converts between slices and arrays explicitly. Array to slice: arr[:] makes a slice that shares the array's memory, so changes show in both. Slice to array: since Go 1.20 you can write [4]int(s) and the data is copied; the conversion panics if the slice is shorter than the array. A conversion to an array pointer, (*[4]int)(s), shares memory.
s := []int{1, 2, 3, 4}
a := [4]int(s) // copy
p := (*[4]int)(s) // shares memory
a[0] = 9 // s unchanged
p[1] = 8 // s[1] is now 8This is useful when an API wants a fixed-size array, for example a hash digest, and you hold a slice.
Practice. Convert a 32-byte slice to an array and show which conversion shares memory.
Maps and the Comma-Ok Idiom Core
A map is a hash table: m := map[string]int{"a": 1} or make(map[string]int). Keys must be comparable (strings, numbers, booleans, structs of comparable fields), and values can be anything. Reading a missing key gives the zero value, which can hide bugs, so use the comma-ok form:
v, ok := m["key"]
if !ok {
// key not present
}Remove with delete(m, key). A nil map can be read but writing to it panics, so always create it first. Maps are not safe for concurrent writes; guard them with a mutex or use sync.Map for special cases. The same comma-ok pattern is used for type assertions and channel receives.
Practice. Count word frequencies in a text and print the words with a count of more than one.
Iterating Maps Core
Use for k, v := range m. Iteration order is deliberately random and differs between runs, so never depend on it. To produce stable output, collect the keys, sort them and loop over the sorted list:
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
slices.Sort(keys)Recent versions also offer maps.Keys and slices.Sorted to shorten this. Deleting entries during a range is safe; adding entries may or may not be visited. If a test compares output built from a map, sort first, or the test will fail at random.
Practice. Print a map in key order, then write a test that would have been flaky without sorting.
Structs, Embedding Structs and Struct Tags & JSON Core
A struct groups named fields: type User struct { Name string; Age int }. Create values with field names (User{Name: "Asha"}), which survives later field additions. Structs are comparable if all fields are, and are copied on assignment.
Embedding a type without a field name promotes its fields and methods: if Admin embeds User, then admin.Name works. It is composition with shortcuts, not inheritance, and the outer type does not become a User for type checks.
Struct tags are string annotations read through reflection. The common use is encoding:
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
}
Practice. Define a Person and an Employee that embeds it, and marshal the Employee to JSON with tags.
Pointer Basics, Pointers with Structs, Maps and Slices Core
A pointer holds the address of a value. &x takes an address and *p follows it. Go has pointers but no pointer arithmetic, and the garbage collector keeps pointed-to values alive.
Because Go is call by value, a function that receives a struct gets a copy. Pass a pointer when the function must modify the original, or when the struct is large. Pointers to struct fields are written with a dot (p.Name), with the dereference done for you. Slices and maps already contain internal pointers, so passing them lets the callee change elements, but append inside the callee will not change the caller's length.
A nil pointer dereference causes a panic, so check for nil where it can legitimately occur. Do not return pointers just to save copying small values.
Practice. Write one function that fails to update a struct and one that succeeds, and explain the difference.
Methods, Pointer and Value Receivers Core
A method is a function with a receiver: func (u User) Greeting() string. Methods vs functions: a method belongs to a type and can satisfy an interface, while a plain function cannot.
Value receivers work on a copy. Pointer receivers can change the original and avoid copying. Choose a pointer receiver when the method modifies state, when the struct is big, or when it contains a mutex that must not be copied. Do not mix receiver kinds on one type without a reason.
Method sets matter for interfaces: a value of type T has only value-receiver methods, while *T has both. So if Save has a pointer receiver, only *T satisfies an interface that includes Save. Go will call pointer methods on addressable variables automatically.
Practice. Create a Counter type with an Increment method and show what breaks when the receiver is a value.
Stage 4 Interfaces, Errors and Generics
Goal. Design small interfaces, handle errors in the idiomatic way and write simple generic code.
Interfaces Basics Core
An interface lists method signatures, and any type that has those methods satisfies it, with no implements keyword. This implicit satisfaction lets the consumer define the interface it needs.
type Reader interface {
Read(p []byte) (n int, err error)
}Guidelines that interviewers expect: keep interfaces small (one to three methods), define them where they are used, accept interfaces and return concrete types, and do not create an interface until a second implementation or a test needs one. Famous examples are io.Reader, io.Writer, fmt.Stringer and error.
An interface value holds a type and a value. An interface holding a nil pointer is itself not nil, which is a well-known trap when returning errors.
Practice. Define a Shape interface, implement it for two types and write a function that sums areas.
Empty Interface, Type Assertions and Type Switches Core
The empty interface, interface{} or since Go 1.18 the alias any, accepts every value. It gives up compile-time checking, so use it sparingly, for example in JSON decoding into unknown shapes.
To get the concrete value back, use a type assertion: s, ok := v.(string). Without the second result, a failed assertion panics. A type switch handles several types at once:
switch x := v.(type) {
case int:
fmt.Println("int", x+1)
case string:
fmt.Println("string", len(x))
default:
fmt.Println("other")
}Embedding interfaces composes them: type ReadWriter interface { Reader; Writer }. With generics available, prefer type parameters to any where you can.
Practice. Write a describe(v any) function that returns a sentence for int, string, slices and anything else.
Error Handling Basics Core
Go has no exceptions for normal failures. A function that can fail returns an error as its last value, and the caller checks it straight away:
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("open config: %w", err)
}The error interface is just Error() string, so any type with that method is an error. Create simple ones with errors.New("text"), formatted ones with fmt.Errorf. Add context as the error moves up the call stack, but handle it only once: either log it or return it, not both.
Do not ignore errors with _ unless you have thought about it. Errors from deferred Close calls on writers also matter.
Practice. Write a function that reads and parses a config file and returns errors that say which step failed.
Wrapping, Sentinel and Custom Errors Core
fmt.Errorf("...: %w", err) wraps an error so the original is still reachable. Inspect the chain with errors.Is(err, target) to compare with a value and errors.As(err, &target) to find a typed error. errors.Unwrap peels one layer, and errors.Join combines several.
Sentinel errors are package-level values such as io.EOF or sql.ErrNoRows, declared with var ErrNotFound = errors.New("not found") and compared with errors.Is. Custom error types carry data:
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return "invalid " + e.Field }Export a sentinel or type only if callers must react to it; every exported error becomes part of your API.
Practice. Define a not-found sentinel and a validation error type, wrap them twice, and detect each with errors.Is and errors.As.
panic and recover Core
panic stops normal execution, runs deferred functions while unwinding and ends the program with a stack trace unless it is recovered. It is for programmer mistakes and impossible states, such as an index out of range or a nil map write. It is not for expected failures like a missing file.
recover works only inside a deferred function and returns the panic value:
defer func() {
if r := recover(); r != nil {
log.Printf("recovered: %v", r)
}
}()Use it at boundaries, such as an HTTP server that must keep serving after a handler bug, and convert the panic into an error or a 500 response. A panic in one goroutine that is not recovered there kills the whole process.
Practice. Write a worker that recovers from a panic in a task, logs it and carries on to the next task.
Why Generics? Functions and Type Inference Core
Generics, added in Go 1.18, let one function or type work across several types while staying type-safe. Before them you chose between copy-pasting code and interface{} with runtime assertions.
func Map[T, U any](xs []T, f func(T) U) []U {
out := make([]U, 0, len(xs))
for _, x := range xs {
out = append(out, f(x))
}
return out
}Type parameters go in square brackets. The compiler infers them from the arguments, so you usually call Map(nums, strconv.Itoa) without writing them out. Generic functions are best for containers and algorithms (filtering, mapping, ordered sets). If you only need behaviour, a plain interface is still simpler.
Practice. Write generic Filter and Reduce functions and use them on ints and strings.
Generic Types / Interfaces and Type Constraints Recommended
A generic type has parameters too: type Stack[T any] struct { items []T }, with methods declared as func (s *Stack[T]) Push(x T). Methods cannot add their own type parameters.
A constraint states what a type argument may do. any allows everything, comparable allows ==, and an interface can list types with a union:
type Number interface {
~int | ~int64 | ~float64
}The tilde means any type whose underlying type is that one. The cmp.Ordered constraint and the slices and maps packages cover most needs. Do not reach for generics early: write the concrete version first and generalise when duplication appears.
Practice. Build a generic Set[T comparable] with Add, Has and Len methods and a Sum function constrained by Number.
Stage 5 Concurrency
Goal. Write concurrent programs with goroutines, channels and contexts, and find races before they ship.
Goroutines Core
A goroutine is a function running concurrently, started with go f(). Goroutines are cheap: they start with a small stack that grows as needed, and the runtime scheduler multiplexes many of them onto a few operating system threads. Tens of thousands in one process are normal.
The program ends when main returns, even if goroutines are still running, so you need a way to wait. Goroutines are not garbage collected while blocked, so a goroutine waiting forever on a channel is a leak. Always know how each goroutine will finish.
Concurrency is not parallelism: concurrency is structuring work as independent tasks, parallelism is running them at the same time on several cores. GOMAXPROCS controls the number of cores used and defaults to all of them.
Practice. Start ten goroutines that print their index, and fix the program so that all of them finish before main exits.
Channels, Buffered vs Unbuffered Core
A channel passes values between goroutines: ch := make(chan int). Send with ch <- v, receive with v := <-ch. An unbuffered channel makes the sender wait until a receiver is ready, so it also synchronises the two. A buffered channel, make(chan int, 10), lets senders continue until the buffer is full.
Close a channel with close(ch) to tell receivers that no more values come; only the sender should close it, and sending on a closed channel panics. Receiving from a closed channel returns the zero value immediately, and v, ok := <-ch tells you which case happened. for v := range ch loops until close. A nil channel blocks forever, which is occasionally useful inside select.
Channel direction types, chan<- int and <-chan int, document intent in function signatures.
Practice. Build a producer that sends numbers 1 to 10 on a channel and a consumer that sums them after the channel closes.
The select Statement Core
select waits on several channel operations and runs the one that is ready; if more than one is ready, it picks at random. A default case makes it non-blocking.
select {
case msg := <-in:
handle(msg)
case <-time.After(2 * time.Second):
return errors.New("timeout")
case <-ctx.Done():
return ctx.Err()
}Typical uses are timeouts, cancellation, merging inputs and non-blocking sends. Prefer time.NewTimer over time.After in hot loops so the timer can be stopped. An empty select {} blocks forever. Remember that a break inside a select case only leaves the select, not the surrounding loop.
Practice. Write a function that waits for a result channel or a one second timeout, whichever comes first.
The sync Package, WaitGroups and Mutexes Core
When goroutines share memory, sync provides the tools. A sync.WaitGroup counts running work: call Add before starting a goroutine, Done when it finishes and Wait to block until the count is zero. Since Go 1.25 there is also wg.Go(f) as a shortcut; check your version.
A sync.Mutex protects shared data: call Lock, and release the lock with the matching method using defer straight afterwards. RWMutex allows many readers or one writer. Other helpers are sync.Once for one-time setup, sync.Pool for reusing temporary objects and sync.Map for a few special access patterns. Do not copy a mutex after first use.
mu.Lock()
defer mu.Unlock()
counter++Prefer simple locking over clever channel designs when you only guard a value. The saying is: share memory by communicating, but use a mutex when that is clearer.
Practice. Increment a shared counter from 100 goroutines using a mutex, then try it without and observe the wrong total.
context Package: Deadlines & Cancellations Core
context.Context carries cancellation signals, deadlines and request-scoped values across API boundaries. Create roots with context.Background(), derive children with context.WithCancel, WithTimeout or WithDeadline, and always call the returned cancel function, usually with defer.
Conventions: the context is the first parameter, named ctx; do not store it in a struct; pass it to every call that may block, such as database queries and HTTP requests. Long-running loops check ctx.Done(). When cancelled, ctx.Err() returns context.Canceled or context.DeadlineExceeded.
Use context values only for request-scoped data like a trace ID, with an unexported key type, not for optional function parameters. Contexts are how servers stop work when a client disconnects.
Practice. Call a slow function with a 500 millisecond timeout and make the function stop work when the context ends.
Concurrency Patterns: Worker Pools, Pipelines, Fan-out and Fan-in Recommended
A worker pool starts N goroutines that read jobs from one channel and write results to another, which limits concurrency and protects downstream systems. A pipeline chains stages, each a goroutine reading from an input channel and writing to an output, so data flows through steps such as read, transform and write.
Fan-out means several goroutines read from the same channel to share load. Fan-in merges several channels into one, normally with a WaitGroup that closes the output when all inputs are done.
for i := 0; i < n; i++ {
go func() {
for job := range jobs {
results <- process(job)
}
}()
}Every pattern needs a clear owner for closing channels and a way to cancel, usually a context. The errgroup package (golang.org/x/sync) adds error handling and limits.
Practice. Build a pool of four workers that hash 100 strings, and stop early when the context is cancelled.
Race Detection Core
A data race happens when two goroutines access the same variable at the same time and at least one writes. The result is undefined behaviour that may only appear in production. The race detector instruments memory accesses and reports races it observes: run go test -race ./... in CI, and go run -race or go build -race when investigating.
It only finds races that actually happen during that run, so it needs tests that exercise concurrency. It slows programs and uses more memory, so it is not meant for production.
Fix races by confining data to one goroutine, using channels, guarding with a mutex or using sync/atomic for single counters. Maps and slices written by several goroutines are the usual suspects, and loop variables captured by goroutines were a classic cause before Go 1.22.
Practice. Write a program with a deliberate race, catch it with the detector and fix it.
Stage 6 Standard Library and I/O
Goal. Use the standard library for files, text, JSON, time, logging and basic reflection.
Standard Library Tour Core
Go's standard library is large and good enough that many programs need no third-party code. Packages to know by name: fmt (formatting and printing), os (files, environment, arguments, exit codes), io and bufio (readers and writers), strings, bytes, strconv, sort and slices, maps, math, errors, time, encoding/json, net/http, database/sql, regexp, flag, log and log/slog, testing, sync and context.
Learn to browse documentation with go doc or the package pages. Reading the standard library source is also a good way to learn idiomatic Go, since it is written in plain style with good comments.
Practice. Pick three packages from the list and write a one-line summary of each from memory, then check against go doc.
I/O and File Handling with os and bufio Core
io.Reader and io.Writer are the core abstractions: files, network connections, buffers and HTTP bodies all implement them, so code written against these interfaces is reusable. io.Copy, io.ReadAll and io.TeeReader combine them.
Read a whole small file with os.ReadFile and write one with os.WriteFile. For larger files, open with os.Open, wrap in bufio.NewScanner to read line by line, or bufio.NewReader for more control, and defer f.Close(). Writers should be wrapped in bufio.NewWriter and flushed. The scanner has a line length limit that you can raise with Buffer.
Use filepath.Join for paths, os.MkdirAll for folders and os.Getenv for environment settings. Exit codes come from os.Exit(code), which skips deferred calls.
Practice. Write a program that counts lines, words and bytes of a file given as an argument, like a minimal wc.
Encoding and JSON Core
encoding/json converts between Go values and JSON. json.Marshal(v) returns bytes, and json.Unmarshal(data, &v) fills a pointer. For streams, use json.NewEncoder(w) and json.NewDecoder(r).
Only exported fields are encoded. Struct tags control names and behaviour: json:"id", json:"note,omitempty", json:"-". Unknown JSON shapes decode into map[string]any, where numbers become float64. Call decoder.DisallowUnknownFields() for strict input, and always handle errors from untrusted data.
Custom formats come from implementing MarshalJSON and UnmarshalJSON. Other formats follow the same pattern in encoding/xml, encoding/csv, encoding/gob and encoding/base64. For very hot paths, third-party JSON packages exist, but measure first.
Practice. Decode a JSON API response into a struct with tags, then encode it back with indentation.
The time Package Core
time.Time is a point in time and time.Duration a length of time stored in nanoseconds. Write durations as 5 * time.Second, never as bare numbers.
Go formats times with a reference layout, not letters like YYYY. The reference moment is Mon Jan 2 15:04:05 MST 2006, so you write t.Format("2006-01-02 15:04") and parse with time.Parse using the same style. Store and transmit times in UTC (t.UTC()), convert to a location with t.In(loc) for display and prefer RFC 3339 for interchange.
Compare with Before, After and Equal, not ==. Use time.Since(start) for measuring, time.Sleep sparingly, time.Ticker for repeated work and time.AfterFunc for delayed calls. Inject a clock interface when you need to test time-dependent code.
Practice. Parse a timestamp in one time zone, print it in two others and compute the duration until the next midnight UTC.
Regular Expressions with regexp Recommended
The regexp package implements RE2 syntax, which guarantees matching in time proportional to the input size, so there are no catastrophic backtracking attacks, but it also lacks lookahead and backreferences.
Compile once at package level with regexp.MustCompile and reuse the value, which is safe for concurrent use. Common methods are MatchString, FindString, FindAllString, FindStringSubmatch for capture groups and ReplaceAllString. Raw string literals keep patterns readable:
var re = regexp.MustCompile(`^(\w+)@(\w+)\.com$`)
parts := re.FindStringSubmatch("asha@example.com")If a simple strings.Contains or strings.Cut is enough, use that instead; it is faster and clearer.
Practice. Extract all email-like tokens from a text file and count them by domain.
Logging: log, slog, Zap and Zerolog Core
The classic log package prints lines with timestamps. Since Go 1.21 the standard library includes log/slog, a structured logger that writes key-value pairs as text or JSON, supports levels and lets you attach fields with With.
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("order created", "id", 42, "user", "asha")Structured logs are far easier to search and aggregate. Before slog arrived, teams adopted Zap and Zerolog, which focus on speed and low allocation; they remain common in existing code. For new code, start with slog and swap the handler if you need more.
Good practice: log at the edges, include a request or trace ID, never log secrets, and do not use logging as a substitute for returning errors.
Practice. Add JSON logging with a request ID field to a small program and log at info and error level.
Command Line Flags with flag Recommended
The flag package defines typed command line options:
port := flag.Int("port", 8080, "listen port")
verbose := flag.Bool("v", false, "verbose output")
flag.Parse()After Parse, the pointers hold the values and flag.Args() returns the remaining positional arguments. Usage text is generated from the descriptions. For sub-commands such as tool serve and tool migrate, create a flag.NewFlagSet per command. The package stops at the first non-flag argument and supports single or double dashes.
When you need nested commands, shell completion or generated help, a library like Cobra is the usual step up, covered in the CLI topic later.
Practice. Write a tool with two sub-commands using FlagSets, each with its own options.
Reflection and the unsafe Package Optional
The reflect package inspects types and values at run time: reflect.TypeOf(x), reflect.ValueOf(x), field names, tags and calling methods. It powers encoding/json, ORMs and validators. It is slow, bypasses compile-time checks and panics easily, so use it only when generics or interfaces cannot do the job.
The unsafe package lets you convert pointers, read memory layouts with unsafe.Sizeof and unsafe.Offsetof, and turn bytes to strings without copying (unsafe.String). It breaks type safety and the compatibility promise does not cover it, so leave it to low-level libraries and measured optimisations.
Interviewers rarely expect more than a clear explanation of when each is justified and the cost of using them.
Practice. Write a function that prints the name, type and json tag of every field of any struct passed in.
Stage 7 Modules, Testing and Tooling
Goal. Manage dependencies with modules, test code properly and use the linters and generators that Go teams rely on.
Modules and Dependencies Core
A module is a tree of packages versioned together, described by go.mod. Start with go mod init example.test/app. The file records the module path, the Go version and required modules; go.sum holds checksums that protect against tampered downloads.
Daily commands: go mod tidy adds missing requirements and removes unused ones, go get pkg@version adds or upgrades, go list -m all shows the full graph and go mod vendor copies dependencies into a vendor folder for offline or locked builds. Go uses minimal version selection: it picks the lowest version that satisfies all requirements, which makes builds predictable.
Major versions of v2 and above are part of the import path (example.test/lib/v2). Use replace in go.mod for local development, and go work workspaces for several modules at once.
Practice. Create a module, add a third-party dependency, run go mod tidy and inspect go.mod and go.sum.
Using 3rd Party Packages and Publishing Modules Recommended
Before adding a dependency, check how well maintained it is, what it pulls in and whether the standard library already does the job. Pin versions through go.mod, review upgrades and run govulncheck regularly.
Publishing a module is mostly pushing a repository whose root has a go.mod whose path matches where it lives, then tagging releases with semantic versions such as v1.2.0. The proxy and checksum database fetch tagged versions on demand. Breaking changes need a new major version with a new import path. Write package documentation as comments that start with the name of the thing they describe, since go doc and the package site render them.
Keep exported API small; everything you export is a promise.
Practice. Tag a small library in a local repository as v0.1.0 and import it from a second module with a replace directive.
Testing Package Basics and Table-driven Tests Core
Tests live in files ending _test.go and are functions named TestXxx(t *testing.T). Run them with go test ./.... Signal failure with t.Errorf (continue) or t.Fatalf (stop). t.Helper() marks helper functions, t.Cleanup registers teardown and t.TempDir() provides a scratch folder.
The idiomatic style is a table of cases run as subtests:
tests := []struct{ name string; in, want int }{
{"zero", 0, 0},
{"double", 2, 4},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := Double(tc.in); got != tc.want {
t.Errorf("got %d, want %d", got, tc.want)
}
})
}Use go test -run Name to filter and -v for detail. Fuzzing with go test -fuzz is built in too.
Practice. Write a table-driven test for a function that parses durations like 1h30m, including invalid inputs.
httptest for HTTP Tests, Mocks and Stubs Recommended
net/http/httptest lets you test handlers without a network: httptest.NewRecorder() captures the response, httptest.NewRequest builds a request and httptest.NewServer starts a real local server for client tests.
req := httptest.NewRequest("GET", "/ping", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
// check rec.Code and rec.BodyFor dependencies, small hand-written fakes that satisfy a narrow interface are the Go norm. A stub returns canned values; a mock also records calls and checks them. Libraries such as testify and gomock generate or help with mocks, but a struct with a few function fields is often enough. This is another reason to define interfaces at the point of use.
Practice. Test an HTTP handler that depends on a store interface using a fake store and httptest.
Benchmarks and Coverage Recommended
Benchmarks are functions named BenchmarkXxx(b *testing.B) that loop b.N times (or use for b.Loop() in recent versions). Run go test -bench . -benchmem to see time and allocations per operation. Compare runs with benchstat, and treat single runs as noise.
Coverage comes from go test -cover, and -coverprofile=c.out followed by go tool cover -html=c.out shows which lines ran. Use it to find untested branches, not as a target to chase; 100% coverage can still miss bugs.
Together with the race detector and fuzzing, these flags form the standard quality gate in CI: go vet ./..., go test -race -cover ./....
Practice. Benchmark two ways of building a string and compare allocations with -benchmem.
Linting and Formatting: go vet, staticcheck, golangci-lint and friends Core
gofmt (run by go fmt) ends style debates, and goimports also adds and removes import lines. go vet ships with Go and finds likely mistakes. Third-party analysers go further: staticcheck finds bugs and dead code, revive is a configurable style linter that replaced the deprecated golint, and golangci-lint runs many linters together with one config file, which is the usual CI choice.
govulncheck scans your code and dependencies against the Go vulnerability database and reports only vulnerabilities your code actually calls, which cuts noise.
Enable linters gradually on an existing codebase so that the team fixes warnings instead of ignoring them. Run formatters in the editor and in CI.
Practice. Add golangci-lint with a small config to a project and fix every finding it reports.
go generate, go:embed for embedding and Build Tags Recommended
go generate runs commands named in //go:generate comments, typically to produce code: stringers for enums, mocks, protocol buffer stubs. It is run manually and generated files are normally committed.
The //go:embed directive puts files into the binary at build time, so a web server can ship its templates and static assets in one executable:
//go:embed templates/*.html
var templates embed.FSBuild constraints and tags decide which files compile. A file named x_linux.go builds only on Linux, and a line such as //go:build integration includes it only with -tags integration. Use tags to separate slow integration tests, or platform-specific code. The old // +build syntax is replaced by //go:build.
Practice. Embed an HTML template into a binary and add an integration test file guarded by a build tag.
Building Executables and Cross-compilation Core
go build writes an executable named after the module. Cross-compiling is a matter of environment variables: GOOS=linux GOARCH=arm64 go build produces a Linux ARM binary on any machine, as long as cgo is not involved. Set CGO_ENABLED=0 for a fully static binary that runs in an empty container image.
Compiler and linker flags: -ldflags "-s -w" strips symbols and debug data for smaller files, -ldflags "-X main.version=1.2.3" sets a string variable at build time, -trimpath removes local paths and -race turns on the race detector. go build -gcflags=-m shows optimisation decisions such as escape analysis.
Check what a binary contains with go version -m binary.
Practice. Build a static Linux binary from your laptop, stamp a version into it with ldflags and print it on startup.
CGO Basics and Plugins Optional
cgo lets Go call C code: a comment above import "C" holds C declarations, and Go then uses C.function. It costs speed per call, complicates cross-compilation, adds a C toolchain dependency and disables fully static builds by default. Use it when you must link a C library, and prefer pure Go packages otherwise.
The plugin package loads shared libraries at run time, but it works only on a few platforms, requires identical toolchain and dependency versions, and is awkward in practice. Most teams choose separate processes with gRPC, or a plugin model based on interfaces compiled in. Plugins and dynamic loading are worth knowing mainly to explain why they are rare.
Practice. Call a one-line C function from Go with cgo and then rewrite the same function in plain Go.
Stage 8 Web Services, Data and Production
Goal. Build, test and profile a networked service backed by a database, and reason about memory use.
Web Development with the net/http Standard Library Core
The standard net/http package is enough for production services. A handler is anything with ServeHTTP(w, r), usually a function func(w http.ResponseWriter, r *http.Request). Since Go 1.22 the default ServeMux supports methods and path parameters:
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "user %s", r.PathValue("id"))
})
http.ListenAndServe(":8080", mux)Always build an http.Server with read, write and idle timeouts, shut it down gracefully with Shutdown(ctx), and use http.Client with a timeout (never the default client in production). Middleware is a function that wraps a handler. Read bodies with limits using http.MaxBytesReader. See API Design Roadmap for the wider design questions.
Practice. Build a JSON API with two routes, a logging middleware and graceful shutdown on interrupt.
Web Frameworks: gin, echo, fiber and beego Optional
Frameworks add routing, binding, validation and middleware on top of or instead of net/http. Gin and Echo are popular, built around the standard handler model with a context object. Fiber has an Express-like API and is built on fasthttp, which does not implement the standard interfaces, so standard middleware does not drop in. Beego is a larger full-stack framework with an ORM and tooling.
Many Go teams use the standard library plus a small router such as chi, because the 1.22 mux closed much of the gap. Pick a framework for team familiarity and ecosystem, not for benchmark charts, and keep business logic independent of it so that switching stays cheap.
Practice. Implement the same endpoint in the standard library and in one framework and compare the code.
Realtime Communication Optional
For server push, Go supports WebSockets through third-party packages such as gorilla/websocket and coder/websocket, and Server-Sent Events with plain net/http by flushing a text/event-stream response. Each connection is typically one goroutine for reading and one for writing, which Go handles well.
Melody is a small library for WebSocket sessions and broadcasting. Centrifugo is a standalone realtime messaging server written in Go that sits next to your application, handles connections and channels, and receives publishes from your backend; it is useful when you do not want to hold connections in the main app.
Design for reconnection, heartbeat pings, back-pressure for slow clients and limits per connection.
Practice. Build a chat room where messages typed in one browser tab appear in another using WebSockets or SSE.
Databases: database/sql, pgx, GORM and ORMs Core
database/sql is the standard interface to relational databases; you import a driver for its side effect. Key points: sql.DB is a connection pool, not one connection, so create it once; use QueryContext, ExecContext and QueryRowContext; always close Rows; use placeholders ($1 or ?) to prevent SQL injection; handle sql.ErrNoRows.
pgx is a popular PostgreSQL driver with its own faster interface and pooling. Query generators like sqlc turn SQL files into typed Go code. ORMs and DB access layers such as GORM map structs to tables; they speed up simple CRUD but can hide queries, so look at the SQL they emit. See SQL Roadmap and Redis Roadmap for the data side.
Wrap multi-step changes in transactions, set pool limits and keep migrations in version control.
Practice. Write a small repository package with database/sql that supports create, get and list, with a transaction for a transfer.
gRPC and Protocol Buffers Recommended
gRPC is a remote procedure call framework using HTTP/2 and Protocol Buffers, a compact binary format described in .proto files. You write the service definition once, run protoc (or buf) to generate Go client and server code, and implement the generated interface.
It supports unary calls and streaming in either direction, deadlines carried through context, metadata and interceptors for logging and auth. Compared with JSON over HTTP it is smaller, typed and faster, but harder to inspect from a browser, which is why many public APIs stay REST. Evolve schemas by adding new fields with new numbers and never reusing a number.
Practice. Define a one-method service in a proto file, generate the code and call it from a Go client.
Building CLIs: Cobra, urfave/cli and bubbletea Recommended
Go is a popular choice for command line tools because of single-file distribution. Cobra is the most used library, providing nested commands, flags, generated help and shell completion; it powers many well-known tools. urfave/cli is a lighter alternative with a similar feature set. Reach for the standard flag package for tiny tools.
Bubbletea is a framework for interactive terminal interfaces based on the Elm architecture: a model, an update function reacting to messages and a view function that returns a string. Good CLI habits include meaningful exit codes, output to standard output and errors to standard error, a --json option for scripts and respecting the NO_COLOR setting.
Practice. Build a todo command line tool with add, list and done sub-commands stored in a JSON file.
Memory Management in Depth: Garbage Collection and Escape Analysis Core
Go allocates on the stack or the heap. The compiler's escape analysis decides: if a value's address outlives the function (returned pointer, stored in an interface or captured by a long-lived closure), it goes to the heap. Check with go build -gcflags=-m. Stack allocation is nearly free; heap allocation costs time and later garbage collection work.
The garbage collector is concurrent and tri-colour mark and sweep: it runs mostly alongside your code with short pauses. It is tuned with GOGC (how much the heap may grow before a cycle) and GOMEMLIMIT (a soft memory ceiling, helpful in containers). Reduce pressure by preallocating slices, reusing buffers with sync.Pool and avoiding needless pointers and conversions. Memory leaks in Go are usually goroutines or references kept in global maps, not forgotten frees.
Practice. Use gcflags -m on a small function to see which values escape, then change the code so one stops escaping.
Profiling and Debugging: pprof, trace and Stack Traces & Debugging Recommended
Measure before tuning. pprof samples CPU, heap, goroutines and blocking. Expose it with import _ "net/http/pprof" on an internal port, or write profiles from tests with -cpuprofile and -memprofile, then explore with go tool pprof and its flame graph view. go tool trace records scheduler, goroutine and GC events for diagnosing latency.
For debugging, read panic output from the top: the first lines say what happened, the stack lists the call path with file and line. runtime/debug.Stack() prints the current trace, sending SIGQUIT dumps all goroutines (a good way to find deadlocks) and the dlv command is the debugger for breakpoints and inspection. The runtime also detects total deadlock and exits with a message.
Practice. Profile a deliberately slow function with pprof and cut its running time by half.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Word frequency command line toolBeginner
Read one or more text files, count word frequencies and print the top N, with a flag for N and for case-insensitive counting. Handle missing files with clear errors and a non-zero exit code.
Packages and flags · Maps and sorting · File I/O · Error handling
- Concurrent link checkerIntermediate
Given a list of addresses from a file, check each with a limited number of workers, apply a per-request timeout and print a sorted report of status codes and failures. Stop cleanly on interrupt.
Goroutines and channels · Worker pools · context · net/http client
- Bookmarks JSON APIIntermediate
Build a REST API for bookmarks with create, list, get and delete, validation, logging middleware and tests using httptest. Start with an in-memory store behind an interface.
net/http · Interfaces · JSON · Table-driven tests
- URL shortener with a databaseAdvanced
Add PostgreSQL or SQLite storage, migrations, graceful shutdown and a rate limiter per client. Package it as a static binary in a minimal container and add a benchmark for the redirect path.
database/sql · Transactions · Middleware · Cross-compilation
- In-memory cache libraryAdvanced
Write a generic cache with expiry and a size limit using a least recently used policy. Make it safe for concurrent use, run the race detector, publish it as a module and document it.
Generics · Mutexes · Benchmarks · Module publishing
Interview questions
Try to answer each question out loud before you open the answer.
What is the difference between an array and a slice in Go?Junior
An array has a fixed length that is part of its type and is copied when assigned or passed. A slice is a header holding a pointer to an array, a length and a capacity. Passing a slice copies only the header, so the callee can change shared elements. Appending may allocate a new array when capacity runs out, which is why you write s = append(s, x). Slices are the everyday choice; arrays are for fixed-size data and map keys.
How does Go pass arguments to functions?Junior
Always by value. A copy of the argument is made, but what is copied differs by type. For an int or struct, you get a full copy. For a pointer, slice, map, channel or function, you copy a small header or reference, so the callee can change shared data. To let a function modify a struct, pass a pointer. Saying that Go has no pass by reference, only pointers passed by value, is the precise answer.
What does the zero value mean and why is it useful?Junior
Every declared variable starts with a defined zero value: 0, false, an empty string or nil. This removes uninitialised memory bugs. Good Go types are designed so that their zero value is ready to use, like sync.Mutex, bytes.Buffer and a nil slice with append. It reduces the need for constructors and makes struct embedding simple. A nil map is the exception that surprises people, since reads work but writes panic.
How do interfaces work, and what does implicit satisfaction give you?Junior
An interface is a set of methods. Any type that has them satisfies it, with no declaration. That lets a package define the small interface it needs, and lets callers pass types written elsewhere, including test fakes. It decouples packages and avoids inheritance hierarchies. The cost is that satisfaction is less visible, so I add a compile-time check such as var _ Store = (*DB)(nil) where it matters.
Why can an interface holding a nil pointer be non-nil?Mid
An interface value has two parts: a dynamic type and a dynamic value. It is nil only when both are unset. If you return a typed nil pointer, say (*MyErr)(nil), as an error, the interface has a type, so err != nil is true. The fix is to return a plain nil explicitly when there is no error, and never return a typed nil pointer through an interface.
Explain the difference between buffered and unbuffered channels.Junior
An unbuffered channel hands over a value directly, so the sender blocks until a receiver is ready and the two goroutines synchronise. A buffered channel has a queue; sends block only when it is full and receives block when it is empty. Use unbuffered for handshakes and ordering, buffered to absorb bursts or to limit work in flight. Buffers do not fix a design problem: a larger buffer just delays the block.
How do you stop a goroutine?Mid
There is no way to kill one from outside. You signal it to stop and it returns. The usual signal is a context: the goroutine selects on ctx.Done() alongside its work, and the owner calls cancel. A closed done channel works too. I also make sure someone waits for it, using a WaitGroup or errgroup, otherwise the program may exit before cleanup finishes, or the goroutine may leak.
What is a data race and how do you find and prevent one?Mid
A data race is unsynchronised access to the same memory from several goroutines where at least one access is a write. Behaviour is undefined. I find races with go test -race in CI and with realistic concurrent tests. I prevent them by confining data to one goroutine, passing ownership through channels, protecting shared state with a mutex or using sync/atomic for counters. Concurrent map writes are a common case.
How does error wrapping work and when do you use errors.Is versus errors.As?Mid
fmt.Errorf with %w wraps an error and keeps the original reachable. errors.Is walks the chain and checks whether any error equals a target, such as a sentinel like sql.ErrNoRows. errors.As walks it and finds an error of a given type, copying it into a variable so I can read its fields. I wrap to add context at each layer, and export only those errors callers need to inspect.
When would you use panic?Mid
For situations that should never happen and cannot be handled meaningfully: a violated invariant, impossible state or failed initialisation at startup, such as regexp.MustCompile with a bad constant pattern. Not for ordinary failures such as invalid input or missing files; those return errors. Libraries should not panic across their API. At service boundaries I recover from panics so a handler bug does not take the process down, then log and return a 500.
How do generics work in Go and when should you avoid them?Mid
Functions and types take type parameters with constraints, and the compiler checks them and infers arguments where it can. They are good for containers and algorithms that behave the same across types, like map, filter, set and cache. I avoid them when behaviour differs per type, since an interface expresses that better, or when only one concrete type exists today. Premature generics make code harder to read.
Describe how slices grow and a pitfall of sharing backing arrays.Mid
When append exceeds capacity, Go allocates a larger array, copies the elements and returns a header pointing at it. Before that point, two slices over the same array see each other's writes. So appending to a sub-slice can overwrite the parent's elements, and after growth the two diverge unpredictably. To be safe, use a full slice expression such as s[a:b:b] to cap capacity, or copy the data, and always use the result of append.
How do you structure a worker pool and shut it down cleanly?Senior
Create a jobs channel and start N workers that range over it, sending results on a results channel. The producer closes jobs when finished. A WaitGroup counts workers, and a separate goroutine waits and then closes results. Add a context so workers abandon work on cancellation, and decide who owns each channel: only the sender closes. For errors I use errgroup, which cancels siblings when one fails.
What does the garbage collector cost and how do you reduce its work?Senior
The collector is concurrent, so it uses CPU alongside the program and causes short pauses. Cost grows with the number of live pointers and with allocation rate. To reduce it: allocate less by preallocating slices, reuse buffers with sync.Pool, avoid unnecessary pointers and interface conversions, and keep values on the stack. I confirm with heap profiles and escape analysis output, and tune GOGC or GOMEMLIMIT only after measuring.
How would you design a graceful shutdown for an HTTP service?Senior
Listen for SIGINT and SIGTERM using signal.NotifyContext. When the signal arrives, call server.Shutdown(ctx) with a deadline, which stops accepting new connections and waits for in-flight requests. Cancel background workers via a shared context, wait for them with a WaitGroup, then close database pools and flush logs. Readiness checks should fail first so a load balancer stops routing traffic.
How does the Go scheduler run goroutines?Senior
It multiplexes goroutines onto operating system threads using a work-stealing scheduler with logical processors, usually one per core. Each processor has a run queue; idle processors steal from others. When a goroutine blocks on a channel or system call, the thread moves on to other goroutines. Since Go 1.14 scheduling is preemptive, so a tight loop no longer starves others. It is why goroutines are cheap compared with threads.
Common mistakes
- Ignoring returned errors with the blank identifier, which hides failures; check every error or comment why it is safe to skip.
- Shadowing err with := inside a block and then returning the outer nil value; use = when you mean to assign.
- Starting goroutines without a plan to stop or wait for them; give every goroutine an owner, a context and a WaitGroup.
- Writing to a shared map or counter from several goroutines; add a mutex or an atomic and run tests with -race.
- Creating interfaces before they are needed, and large ones; define small interfaces at the point of use.
- Using an http.Client or http.Server without timeouts; set them explicitly in every production service.
- Forgetting that append may reallocate, and using stale slices; always assign the result back.
- Using pointers everywhere to avoid copying; use values for small types and measure before optimising.
- Calling defer inside a long loop so resources stay open; move the body into a function that returns each iteration.
Ready-for-interview checklist
- I can write a small program with packages, structs, methods and tests without a tutorial.
- I can explain slices, capacity and what append does.
- I can say what the zero value is for each basic type and why it is useful.
- I can design a small interface and explain why the consumer should own it.
- I can wrap, check and expose errors with errors.Is and errors.As.
- I can start goroutines safely and stop them with a context.
- I can choose between a channel and a mutex for a given problem.
- I can find and fix a data race using the race detector.
- I can write a generic function with a constraint, and explain when not to.
- I can manage a module, run go mod tidy and explain go.sum.
- I can write table-driven tests, a benchmark and an httptest handler test.
- I can build and profile an HTTP service, then ship it as a static binary.
- I can explain escape analysis and what the garbage collector costs.
Related roadmaps
- Rust RoadmapOwnership, borrowing, traits, error handling and async.
- Modern C++ RoadmapModern C++, RAII, templates, STL, memory and performance.
- Docker RoadmapImages, containers, networking, volumes, Compose and security.
- Kubernetes RoadmapPods, deployments, services, config, scaling and operations.
- API Design RoadmapREST, gRPC, GraphQL, versioning, auth, pagination and rate limits.
- SQL RoadmapQueries, joins, window functions, indexes and transactions.
FAQ
How long does it take to learn Go?
If you already program, the language itself takes two to three weeks. Reaching interview level, including concurrency, testing and a web service, usually takes ten to fourteen weeks at around eight hours a week. Writing projects matters more than reading.
Is Go a good first programming language?
It can be. The syntax is small and the tooling is simple. The weak point is that beginners meet pointers, interfaces and concurrency earlier than in some languages. If you are new to programming, spend a week on basics first, then follow the stages in order.
Is Go still worth learning?
Yes, if you want backend, platform or infrastructure work. Much cloud and DevOps software is written in it, and its compatibility promise means skills stay useful for years. It is a weaker choice for machine learning, mobile apps or rich desktop interfaces.
Should I learn Go or Rust first?
Learn Go first if you want to be productive on services quickly. Learn Rust first if you want to understand memory and ownership deeply or work close to the system. They complement each other; the Rust Roadmap roadmap covers the second path.
Do I need to learn generics for interviews?
You should understand them and write a simple generic function, but most Go interviews focus on slices, maps, interfaces, errors and concurrency. Generics come up as a design discussion about when to use them.