Golang / GoLang Interfaces and Object Oriented Interview Questions
How is context.Context an interface and how does its design demonstrate Go best practices?
context.Context is a four-method interface that carries deadlines, cancellation signals, and request-scoped values across API boundaries. Its design exemplifies Go's interface philosophy: small, behaviour-focused, implicitly satisfied, and composable.
// The full context.Context interface: type Context interface { Deadline() (deadline time.Time, ok bool) // when will this context expire? Done() <-chan struct{} // closed when context is cancelled Err() error // nil, context.Canceled, or context.DeadlineExceeded Value(key any) any // request-scoped values } // All functions that may block or need cancellation accept context as FIRST param func FetchUser(ctx context.Context, id int) (*User, error) { req, _ := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("/users/%d", id), nil) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var u User return &u, json.NewDecoder(resp.Body).Decode(&u) } // Creating contexts ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // ALWAYS defer cancel user, err := FetchUser(ctx, 42) if err != nil { if errors.Is(err, context.DeadlineExceeded) { log.Println("request timed out") } } // Checking cancellation in a loop func processItems(ctx context.Context, items []Item) error { for _, item := range items { select { case <-ctx.Done(): return ctx.Err() // cancelled default: process(item) } } return nil }
Notice that context.Context is defined as an interface but almost always consumed, never implemented by user code (the standard library provides all concrete implementations: context.Background(), context.WithTimeout, etc.). This is the correct usage: it is a consumer-facing interface that unifies all context types behind one contract, enabling library code to accept any context without caring about its implementation.
More Related questions...