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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
