Go Interview Questions and Answers
Go (Golang) interview questions with answers and code: slices and maps, interfaces, errors, goroutines, channels, select, sync, context, the scheduler, memory and garbage collection, testing and performance.
Key takeaways
- Go interviews focus on slices, maps, interfaces and error handling: the parts with subtle behavior.
- Concurrency is central: goroutines, channels,
select,syncandcontext. - Expect output-prediction questions about slices, closures in loops and nil interfaces.
- Senior roles add the scheduler, memory, profiling and service design in Go.
Contents
Go interviews test whether you understand the language’s simple-looking but subtle semantics and can write correct concurrent code. Below are 29 common questions grouped by topic and level, with code.
What Go interviews cover
Editorial estimate.
- Concurrency35%
- Language semantics25%
- Errors and interfaces15%
- Runtime and performance15%
- Testing and services10%
Channel behavior cheat sheet
| Operation | nil channel | open channel | closed channel |
|---|---|---|---|
| Send | blocks forever | blocks until received (or buffer has space) | panics |
| Receive | blocks forever | blocks until a value arrives | returns zero value, ok == false |
| Close | panics | succeeds | panics |
See also backend, DevOps and system design interview questions.
Language basics
1How do slices work internally?
JuniorA slice is a small header with a pointer to an underlying array, a length and a capacity. Slicing creates a new header over the same array, so changes are visible through both. append writes into the existing array if capacity allows; otherwise it allocates a new, larger array and copies.
2What does this code print?
Mida := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 99)
fmt.Println(a)
[1 2 99 4]. b has capacity 4, so append writes into the shared array and overwrites a[2]. Use a full slice expression a[:2:2] or slices.Clone to avoid sharing.
3How do maps behave in Go?
JuniorMaps are reference-like hash tables. Reading a missing key returns the zero value (use v, ok := m[k] to check), iteration order is random, writing to a nil map panics, and maps are not safe for concurrent writes without synchronization.
4Value receivers vs pointer receivers?
JuniorA value receiver works on a copy; a pointer receiver can modify the original and avoids copying large structs. Be consistent per type. The method set matters for interfaces: if methods have pointer receivers, only the pointer type implements the interface.
5What does defer do, and when are its arguments evaluated?
Middefer schedules a call to run when the function returns, in last-in, first-out order. Arguments are evaluated immediately, when the defer statement runs. It’s typically used for closing resources and unlocking mutexes.
6How do generics work in Go?
MidSince Go 1.18, functions and types can have type parameters with constraints:
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
}
Use them for containers and algorithms; interfaces remain the main tool for behavior.
Interfaces and errors
7How are interfaces implemented in Go?
JuniorImplicitly: any type with the required methods satisfies the interface, without declaring it. This encourages small interfaces defined by the consumer (“accept interfaces, return structs”), such as io.Reader.
8Why can an interface holding a nil pointer be non-nil?
MidAn interface value has a type and a value. If you assign a typed nil pointer, the type is set, so the interface is not nil:
func find() error {
var e *MyErr = nil
return e // err != nil is true for the caller
}
Return an explicit nil for “no error”.
9How do you handle and wrap errors?
MidReturn errors as values, add context with fmt.Errorf("load user %d: %w", id, err), and inspect them with errors.Is (sentinel errors) and errors.As (error types). Handle each error once: either log it or return it, not both.
10When should you use panic?
MidFor truly unrecoverable programmer errors or impossible states, not for normal error handling. Recover only at boundaries such as an HTTP middleware, so one bad request doesn’t crash the server.
Get Go answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.
Concurrency
11What is a goroutine?
JuniorA lightweight thread managed by the Go runtime, started with go f(). Goroutines start with small stacks that grow as needed, so you can run many thousands. The runtime multiplexes them onto OS threads.
12Buffered vs unbuffered channels?
MidAn unbuffered channel synchronizes sender and receiver: a send blocks until someone receives. A buffered channel lets sends proceed until the buffer is full. Closing a channel signals no more values; receiving from a closed channel returns the zero value and ok == false. Sending on a closed channel panics.
13What does select do?
MidIt waits on several channel operations and runs the first one that’s ready (randomly if several are). With a default case it doesn’t block. It’s commonly combined with timeouts and cancellation:
select {
case res := <-results:
return res, nil
case <-ctx.Done():
return nil, ctx.Err()
}
14Channels vs mutexes: when do you use each?
MidChannels are great for passing ownership of data and coordinating goroutines (pipelines, worker pools). A sync.Mutex is simpler for protecting shared state such as a cache. Use whichever makes the code clearer.
15What is sync.WaitGroup used for?
MidWaiting for a group of goroutines to finish: Add before starting them, Done in each, Wait in the coordinator. errgroup.Group from golang.org/x/sync adds error propagation and cancellation.
16How do you avoid goroutine leaks?
MidMake sure every goroutine has a way to exit: pass a context and stop on ctx.Done(), close channels when producers finish, and avoid sends on channels nobody reads. Leaks show up as a growing goroutine count in metrics or pprof.
17Implement a worker pool.
Midfunc process(ctx context.Context, jobs []Job, workers int) []Result {
in := make(chan Job)
out := make(chan Result)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range in {
out <- handle(ctx, j)
}
}()
}
go func() {
defer close(in)
for _, j := range jobs {
select {
case in <- j:
case <-ctx.Done():
return
}
}
}()
go func() { wg.Wait(); close(out) }()
var results []Result
for r := range out {
results = append(results, r)
}
return results
}
18What is context.Context for?
MidCarrying cancellation signals, deadlines and request-scoped values across API boundaries and goroutines. Pass it as the first parameter, never store it in structs, and always call the cancel function returned by WithTimeout or WithCancel.
19How do you detect data races?
JuniorRun tests and binaries with the race detector: go test -race. It finds unsynchronized concurrent access at runtime. Fix races with mutexes, channels or atomics.
Runtime and performance
20How does the Go scheduler work?
SeniorThe G-M-P model: goroutines (G) run on OS threads (M) through logical processors (P), whose number is GOMAXPROCS. Each P has a local run queue; idle Ps steal work from others. Goroutines are preempted to keep long-running ones from starving others, and blocking system calls hand off the P to another thread.
21How does garbage collection work in Go?
SeniorA concurrent, tri-color mark-and-sweep collector with very short pauses. GOGC controls how much the heap may grow before the next collection, and GOMEMLIMIT sets a soft memory limit. Reducing allocations in hot paths is the main way to lower GC cost.
22What is escape analysis?
MidThe compiler decides whether a variable can stay on the stack or must “escape” to the heap, for example when its pointer outlives the function. go build -gcflags=-m shows decisions. Fewer heap allocations mean less GC work.
23How do you profile a Go service?
MidUse pprof: expose net/http/pprof or capture profiles in tests, then inspect CPU, heap, goroutine and block profiles with go tool pprof. Benchmarks (go test -bench) and benchstat measure improvements reliably.
24How do you reduce allocations?
MidPreallocate slices and maps with known sizes, reuse buffers (sync.Pool for short-lived objects), avoid converting between string and []byte repeatedly, and use strings.Builder for concatenation.
Testing and services
25How do you write table-driven tests?
Juniorfunc TestAbs(t *testing.T) {
tests := []struct{ in, want int }{{-2, 2}, {0, 0}, {3, 3}}
for _, tt := range tests {
t.Run(fmt.Sprint(tt.in), func(t *testing.T) {
if got := Abs(tt.in); got != tt.want {
t.Errorf("Abs(%d) = %d, want %d", tt.in, got, tt.want)
}
})
}
}
26How do you structure an HTTP service in Go?
MidThe standard library’s net/http (with method and path patterns since Go 1.22) or a router like chi; handlers that depend on interfaces for storage and external services; middleware for logging, recovery and auth; configuration from the environment; and graceful shutdown with server.Shutdown(ctx).
27How do you set timeouts on HTTP servers and clients?
MidThe default http.Client has no timeout, which can hang goroutines forever. Set Timeout on clients or use contexts with deadlines per request, and set ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout on servers.
28How do Go modules manage dependencies?
Midgo.mod declares the module path and required versions; go.sum records checksums. Go uses minimal version selection, choosing the minimum version that satisfies all requirements, which makes builds reproducible. go mod tidy keeps the files clean.
29How do you design a high-throughput service in Go?
SeniorBound concurrency with worker pools or semaphores, apply backpressure instead of unbounded queues, set timeouts everywhere, propagate context cancellation, pool connections, minimize allocations in hot paths, and expose metrics (latency, goroutines, GC) and pprof for production debugging.
How to prepare
- Know the tricky semanticsSlice sharing, map behavior, nil interfaces, defer evaluation.
- Practice concurrency patternsWorker pools, pipelines, fan-out/fan-in, errgroup and context cancellation.
- Run the race detectorBe ready to explain how you found and fixed a data race.
- Profile something realUse pprof on a small service and explain what you found.
- Write idiomatic codeSmall interfaces, wrapped errors, table-driven tests.
Get answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.