What problem does context.Context solve, and what are its four methods?
context.Context carries three things across API boundaries and goroutines for the lifetime of one request or operation : a cancellation signal , an optional deadline ,…
35 Go interview questions on context, with detailed answers and code.
context.Context carries three things across API boundaries and goroutines for the lifetime of one request or operation : a cancellation signal , an optional deadline ,…
Each cancelable context ( *cancelCtx ) holds a mutex, a lazily created done channel, an err , a cause , and a children map[canceler]struct{} . When you derive a…
Deriving a cancelable context registers the child in its parent's children map. WithTimeout / WithDeadline also start a time.Timer , and a custom parent may cause a…
WithTimeout(parent, d) is exactly WithDeadline(parent, time.Now().Add(d)) . Use a timeout for a relative budget ("this call gets 2s") and a deadline when an absolute…
func main() { parent, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() child, cancelChild := context.WithCancel(parent) defer…
Err() returns nil while Done() is still open. Once it is closed, Err() returns exactly one of two sentinels: context.Canceled : someone called a cancel function, or a…
WithCancelCause (Go 1.20) returns a CancelCauseFunc that takes an error saying why the context was canceled. ctx.Err() still returns only context.Canceled , which keeps…
var errSlow = errors.New("payment provider slow") func main() { ctx, cancel := context.WithTimeoutCause(context.Background(), time.Hour, errSlow) cancel()…
Value compares keys with == on the interface, so both the dynamic type and the value must match. If two packages both use the string "user" , they overwrite each other's…
type ctxKey string func main() { ctx := context.WithValue(context.Background(), ctxKey("user"), "alice") ctx = context.WithValue(ctx, ctxKey("user"), "bob") child,…
Every WithValue call wraps its parent in a valueCtx{Context; key, val any} that stores one pair . Value(k) is a linked-list walk: check this node's key, then move to the…
The official guidance: use context values only for request-scoped data that crosses process and API boundaries , not for passing optional parameters to functions. Good…
The context package docs say: "Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it." The reasons: Lifetime…
Both return an empty context that is never canceled, has no deadline, and holds no values. They behave the same; the difference is intent , which static analysis tools…
func AfterFunc(ctx Context, f func()) (stop func() bool) (Go 1.21) arranges for f to run in its own goroutine once ctx is done. If ctx is already done, f starts right…
Turn the cancellation into something the blocking API does understand. For network connections that means setting a deadline in the past, which makes Read return at once…
WithoutCancel(parent) (Go 1.21) returns a context that keeps the parent's values but is never canceled : Done() returns nil and Err() returns nil . Deadline() returns…
func handler(w http.ResponseWriter, r *http.Request) { go func() { // sends an audit event to another service if err := sendAudit(r.Context(), r.URL.Path); err != nil {…
For incoming server requests, r.Context() is canceled when any of these happens: the client's connection closes; the request is canceled (for example an HTTP/2…
Attach the context with http.NewRequestWithContext (or req.WithContext ). Cancellation then applies to the whole exchange : dialing, TLS, writing the request, waiting…
Use the *Context methods: QueryContext , ExecContext , QueryRowContext , BeginTx , PingContext , and Conn(ctx) . When the context is canceled: A call waiting for a pool…
A common pattern wraps a legacy blocking function in a goroutine and uses select to wait for either the result or ctx.Done() . The trap: if the result channel is…
For channel-driven loops, put ctx.Done() in the same select as the work channel. For CPU-bound loops that never block, check ctx.Err() regularly. Checking every N…
errgroup.WithContext(parent) (from golang.org/x/sync/errgroup ) returns a group and a derived ctx . That ctx is canceled the first time a goroutine returns a non-nil…
The standard library has no merge function, but WithCancelCause plus AfterFunc makes one cheap, without a dedicated watcher goroutine when both inputs are stdlib…
Yes, any type that implements the four methods is a Context, and all methods must be safe for concurrent use. The most common custom context is not written from scratch:…
A context does not travel over the network by itself; frameworks serialize parts of it. gRPC sends the remaining time in the grpc-timeout header. The server rebuilds a…
signal.NotifyContext returns a context that is canceled when one of the listed signals arrives. It is the idiomatic root for a process's lifetime. func main() { ctx,…
Techniques: t.Context() (Go 1.24): a per-test context that is canceled just before t.Cleanup functions run. It replaces context.Background() in tests, and goroutines…
Yes. All Context methods and all cancel functions are safe to call from any number of goroutines. The rules: Done() returns the same channel on every call. For cancelCtx…
Guidelines interviewers expect: Every function that does I/O, blocks, or might be slow takes ctx context.Context as its first parameter. Pure CPU helpers usually don't…
func main() { ctx, cancel := context.WithCancel(context.Background()) cancel() done := make(chan struct{}) stop := context.AfterFunc(ctx, func() { fmt.Println("callback…
var errShutdown = errors.New("shutting down") func main() { parent, cancel := context.WithCancelCause(context.Background()) detached := context.WithoutCancel(parent)…
Since Go 1.23, iterators are plain functions that call yield . The loop body runs synchronously on the caller's goroutine , so there is no producer goroutine to leak.…
Both packages in golang.org/x use a context to make waiting cancelable: (*semaphore.Weighted).Acquire(ctx, n) and (*rate.Limiter).Wait(ctx) block until a slot or token…