Technical Mid Level

What is the purpose of context.Context in Go? Give examples of correct and incorrect usage.

Quick Tip

Show best practices: "Context is always the first parameter, never stored in a struct. I use WithTimeout for external calls, WithCancel for spawned goroutines, and only use Value for truly request-scoped metadata like trace IDs."

What good answers include

Context carries deadlines, cancellation signals, and request-scoped values across API boundaries. Correct usage: pass as the first parameter to functions, use WithTimeout/WithCancel for lifecycle management, check ctx.Err() or select on ctx.Done(). Incorrect usage: storing context in a struct, using context.Value for required dependencies (use function parameters instead), creating contexts with overly long timeouts, or ignoring cancellation in long-running operations.

What interviewers are looking for

Critical for production Go services. Candidates who store context in structs or use Value as a dependency injection mechanism will create maintenance problems. Look for understanding of cancellation propagation.

← All Go questions