Top 10 Go scenario questions
Try each one yourself first, then open the model answer.
1. Memory keeps growing and the number of goroutines never drops. What is wrong?
Show answerHide answer
Goroutines are leaking, usually blocked on a channel or network call. Give them a way to stop with context cancellation or a closed channel, and profile with pprof.
2. main exits before your goroutines finish. How do you wait for them?
Show answerHide answer
Use a sync.WaitGroup, or an errgroup when you also need to collect the first error and cancel the others.
3. Writing to a map from several goroutines crashes the program. What do you do?
Show answerHide answer
Maps are not safe for concurrent writes. Protect them with a sync.Mutex or RWMutex, or use sync.Map for suitable access patterns. Run tests with the race detector.
4. A program panics with 'all goroutines are asleep'. What does it mean?
Show answerHide answer
Every goroutine is blocked, often a send on an unbuffered channel with no receiver. Check who sends, receives and closes each channel.
5. Who should close a channel when several goroutines send on it?
Show answerHide answer
Not an individual sender, since sending on a closed channel panics. Have a coordinator wait for all senders to finish and then close it.
6. Appending to a slice in a function sometimes changes the caller's data and sometimes does not. Why?
Show answerHide answer
Slices share a backing array until append exceeds capacity and allocates a new one. Return the new slice, or copy before modifying.
7. A function returns a nil pointer as an error type and err != nil is true. Explain.
Show answerHide answer
An interface holding a typed nil pointer is not itself nil. Return a literal nil for the error when there is no error.
8. Requests to a slow dependency pile up. How would you protect the service?
Show answerHide answer
Use context with timeouts, limit concurrency with a buffered channel or worker pool, and consider a circuit breaker.
9. You need callers to detect a specific wrapped error. How do you design it?
Show answerHide answer
Wrap with fmt.Errorf and the %w verb, and check with errors.Is for sentinel values or errors.As for error types.
10. Deferred file closes inside a long loop exhaust file descriptors. Why?
Show answerHide answer
defer runs when the function returns, not at the end of an iteration. Move the loop body into its own function or close explicitly.
