Go (Golang) interview questions and answers for developers
Go (Golang) interview questions focus on concurrency and on the few places where Go's simple syntax hides a sharp edge. Expect goroutines, channels and select, sync primitives and context cancellation, implicit interfaces and the nil interface trap, slice internals and append, maps, error wrapping, defer, generics and the race detector. Good answers describe what the runtime does, such as which goroutine blocks and who owns a channel, rather than reciting syntax.
By Evin JohnPublished 8 min read
How Go is tested in interviews
Go is common in backend services, infrastructure tools, cloud platforms and command-line software, so Go interviews lean toward services and concurrency rather than clever language tricks. A typical process has a screen on language basics, a coding exercise written in Go (often something with goroutines such as a rate-limited fetcher or a worker pool), and for experienced candidates a design or debugging conversation about a service that leaked goroutines, raced on shared state or ignored cancellation.
- Basics screenSlices, maps, structs, methods, interfaces, errors. Interviewers listen for idiomatic vocabulary: zero values, receivers, embedding.
- Concurrency exerciseFan out work to goroutines, collect results, stop on the first error or a timeout. Closing channels correctly is part of the grade.
- Code readingA short program with a data race, a leaked goroutine or a typed nil error. Explain what happens and fix it.
- Service designHTTP handlers with context, graceful shutdown, retries, and how you would test and profile the service.
Go fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Array or slice: what is the difference? | Data structures | An array has a fixed length that is part of its type and is copied on assignment. A slice is a small header with a pointer, a length and a capacity that refers to an underlying array. |
| What is a zero value? | Initialization | Every type has one: 0, empty string, false, nil for pointers, slices, maps, channels, functions and interfaces. Good Go types are useful at their zero value, like sync.Mutex. |
| How do interfaces get implemented? | Implicit satisfaction | A type satisfies an interface by having its methods; there is no implements keyword. This lets the consumer define a small interface for exactly what it needs. |
| Value receiver or pointer receiver? | Method sets | Use a pointer receiver to mutate the receiver or avoid copying a large struct. Methods with pointer receivers are not in the value type's method set, so a plain value may not satisfy the interface. |
| What is struct embedding? | Composition | Embedding promotes the inner type's fields and methods to the outer type. It is composition with convenient syntax, not inheritance: there is no virtual dispatch back to the outer type. |
| Is map iteration order stable? | Maps | No. The runtime deliberately varies it. Sort the keys when you need a fixed order. |
| What happens when you write to a nil map? | Maps | It panics. Reading from a nil map returns the zero value, so the bug shows up only at the first write. Initialize with make or a literal. |
| How does Go handle errors? | Error values | Errors are returned as the last value and checked explicitly. Wrap with fmt.Errorf and the %w verb, then test with errors.Is for sentinel values and errors.As for typed errors. |
| When is panic appropriate? | Failure modes | For programmer errors and impossible states, not for expected failures such as a missing file. recover works only inside a deferred function, typically at a goroutine or request boundary. |
type NotFound struct{}
func (*NotFound) Error() string { return "not found" }
func find(found bool) error {
var e *NotFound // nil pointer of a concrete type
if !found {
e = &NotFound{}
}
return e // an interface holding (*NotFound, nil)
}
func main() {
fmt.Println(find(true) == nil) // false
}An interface value is nil only when both its type and its value are nil. Returning a nil pointer through an error interface sets the type, so callers see a non-nil error. The fix is to return a literal nil on the success path.
Slices, append and maps
a := []int{1, 2, 3, 4}
b := a[:2] // len 2, cap 4, shares a's array
b = append(b, 99) // fits in capacity: overwrites a[2]
fmt.Println(a) // [1 2 99 4]
c := a[:2:2] // full slice expression caps capacity at 2
c = append(c, 7) // must allocate a new array
fmt.Println(a) // [1 2 99 4], unchanged by this append- Why must you assign the result of append? It may return a slice that points to a new, larger array. Keeping the old header means losing the appended element.
- How does a slice grow? When capacity runs out, append allocates a bigger array and copies. The growth factor is a runtime detail; what matters is preallocating with make when you know the size.
- Can a small slice keep a large array alive? Yes. Slicing a few bytes out of a large buffer keeps the whole buffer reachable. Copy the bytes you need when the slice outlives the buffer.
- Why are maps not safe for concurrent use? Concurrent writes, or a write during a read, can make the runtime stop the program with a fatal error. Guard the map with a Mutex or RWMutex, or use sync.Map for its narrow cases such as keys written once and read many times.
- Can you take the address of a map element? No, because the map may move entries when it grows. Store pointers as values if you need to mutate in place.
Goroutines, channels and select
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a goroutine, and why is it cheap? | Runtime model | A function running concurrently, scheduled by the Go runtime onto OS threads. It starts with a small stack that grows as needed, so thousands are normal. |
| Unbuffered versus buffered channel? | Synchronization | An unbuffered send waits until a receiver takes the value, which synchronizes the two goroutines. A buffered channel lets sends proceed until the buffer is full. |
| What happens on a closed channel? | Channel rules | Receives drain remaining values, then return the zero value with ok false. Sending on a closed channel panics, and so does closing it twice. |
| Who should close a channel? | Ownership | The sender, and only when receivers need to know no more values are coming. Receivers never close; a channel with several senders needs a coordinator, often a WaitGroup. |
| What does select do when several cases are ready? | select | It picks one at random, which avoids starvation. A default case makes the select non-blocking. |
| What is a nil channel good for? | Advanced select | Sends and receives on a nil channel block forever, so setting a channel variable to nil disables its case in a select loop. |
| How do you add a timeout to a channel receive? | Timeouts | Select on the channel and on ctx.Done() or time.After. In a long loop prefer a context or a reusable timer. |
| What is a goroutine leak? | Lifecycle | A goroutine blocked forever on a channel or lock that nobody will service. It holds memory and anything it references. Every goroutine needs a clear exit path. |
func squareAll(ctx context.Context, jobs <-chan int, workers int) <-chan int {
results := make(chan int)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobs { // the producer closes jobs
select {
case results <- j * j:
case <-ctx.Done():
return
}
}
}()
}
go func() {
wg.Wait()
close(results) // one closer, after every sender is done
}()
return results
}sync primitives, context and the race detector
- Channels or a mutex? Channels suit passing ownership of data and signaling events. A mutex suits protecting a small piece of shared state. Picking the simpler one for the job is the idiomatic answer.
- What is sync.WaitGroup for, and what is the common mistake? Waiting for a set of goroutines. Call Add before starting the goroutine, not inside it, or Wait may return early.
- When is RWMutex worth it? When reads vastly outnumber writes and the critical section is long enough that parallel readers help. For short sections a plain Mutex is often as fast.
- What does sync.Once guarantee? The function runs exactly once even with concurrent callers, and every caller sees its effects after Do returns.
- Why pass context.Context as the first parameter? It carries cancellation, deadlines and request-scoped values down the call tree. Do not store it in structs, and always call the cancel function a constructor returns.
- What belongs in context values? Request-scoped data such as a trace ID. Not optional parameters, not dependencies.
- How do you find data races? Run tests and staging builds with the
-raceflag. It reports races that actually happen during the run, so it only finds what your tests exercise. - What does errgroup add over WaitGroup? From the golang.org/x/sync module, it collects the first error and, with WithContext, cancels the others when one fails.
defer, generics and loop variables
func count() (n int) {
defer func() { n++ }()
for i := 0; i < 3; i++ {
defer fmt.Print(i, " ") // i is evaluated now
}
return 10
}
// Calling count() prints "2 1 0 " and returns 11.func Map[T, U any](in []T, f func(T) U) []U {
out := make([]U, 0, len(in))
for _, v := range in {
out = append(out, f(v))
}
return out
}
lengths := Map([]string{"go", "rust"}, func(s string) int { return len(s) })
// [2 4]- When are deferred arguments evaluated? At the defer statement, not when the deferred call runs. A closure reads variables when it runs instead.
- Why can defer in a loop be a problem? Deferred calls wait for the function to return, so closing files in a long loop with defer keeps them all open. Move the body into its own function.
- When should you use generics? For containers and algorithms that work the same for many types, such as a set or a Map helper. Interfaces remain the better tool when behavior differs by type.
- What do `any` and `comparable` mean as constraints? any accepts every type; comparable allows == and !=, which you need for map keys in a generic set.
- What changed for loop variables in Go 1.22? Each iteration of a for loop now gets its own variable, so goroutines and closures created in the loop no longer all see the last value. Code that targets older versions in go.mod keeps the old behavior.
Senior and scenario questions
| Scenario | What it tests | What a strong answer shows |
|---|---|---|
| Memory and goroutine count rise slowly in production. | Leak hunting | Check the goroutine profile from pprof, find the stack most goroutines are parked on, and look for a missing cancel, an unread channel or a missing timeout on an HTTP client. |
| An HTTP handler keeps working after the client disconnects. | Cancellation | Use r.Context() and pass it to database and outbound calls so they stop when the request is canceled. |
| The service must shut down without dropping requests. | Lifecycle | Catch the signal, call Server.Shutdown with a deadline, stop accepting work, drain workers and close resources in order. |
| CPU spikes during JSON-heavy endpoints. | Profiling | Take a CPU profile, look for allocation hot spots, reuse buffers, and measure again rather than guessing. |
| A package exposes a large interface that callers must mock. | API design | Return concrete types and let consumers define small interfaces. Accept interfaces, return structs is the usual rule of thumb. |
Fictional example
- I would cap concurrency at a fixed number, say ten, with a buffered channel used as a semaphore or an errgroup with SetLimit. Each fetch gets the parent context so a timeout or the first fatal error stops the rest, and each HTTP request uses that context. Results go into a slice indexed by position, so no mutex is needed and order is preserved. In a crawler I worked on, the first version spawned one goroutine per URL with no limit and was rate limited by the remote site within seconds; adding the limit and a per-host backoff fixed it. Before shipping I would run the tests with the race detector and add one test that cancels midway to prove nothing leaks.
Two-week Go preparation plan
- Days 1 to 3: slices, maps, structs, methods and interfaces. Reproduce the append aliasing and typed nil examples and explain them aloud.
- Days 4 to 7: goroutines and channels. Build a pipeline, a worker pool and a fan-in, each with clean shutdown, and run them with the race detector.
- Days 8 to 10: context and errors. Add timeouts and cancellation to an HTTP client, wrap errors with %w and test them with errors.Is and errors.As.
- Days 11 and 12: generics, defer details and table-driven tests with subtests.
- Days 13 and 14: a timed mock: a small HTTP service with graceful shutdown and a concurrent batch job, then profile one endpoint with pprof.
Go pairs naturally with two other systems-minded languages in this set: Rust interview questions push ownership into the type system, and Kotlin interview questions cover coroutines, a different take on lightweight concurrency. For the role around the language, see backend developer interview questions.
Concurrency answers fall apart when spoken too fast, so record a few. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a mock Go interview that you can reread to see whether you explained who closes the channel. In practice sessions it can read a Go exercise from a screenshot, offer a hint or a full approach, and with Pro or the free trial take the résumé and job description you add into account. Your sessions and notes remain available for review.
Questions people ask
What Golang questions are asked in interviews?
Expect slices and maps, value and pointer receivers, implicit interfaces and the typed nil error, error wrapping, defer, and a lot of concurrency: goroutines, channels, select, WaitGroup, Mutex and context cancellation.
How do I prepare for Go concurrency interview questions?
Build a pipeline, a worker pool and a fan-in with clean shutdown, add context timeouts, and run every exercise with the race detector. Be ready to say which goroutine closes each channel and how each goroutine exits.
What Go topics matter for experienced developers?
Goroutine leaks and pprof, graceful shutdown, cancellation through HTTP and database calls, API design with small interfaces, generics where they fit, and performance work driven by profiles.
Is Go the same as Golang in job posts?
Yes. The language is called Go; Golang is the common search term and comes from the old golang.org address. Job posts use both.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
