Golang / GoLang Basics Interview Questions
What is context.Context and why is it the first parameter in so many Go functions?
context.Context is Go's standard mechanism for propagating three things across API boundaries and goroutine calls: cancellation signals, deadlines, and request-scoped values. Passing it as the first parameter is a Go convention — it allows any blocking call to be cancelled.
// The context.Context interface:
// Done() <-chan struct{} — closed when cancelled or deadline passed
// Err() error — nil, Canceled, or DeadlineExceeded
// Deadline() (time.Time, bool)
// Value(key) any
// Root contexts
ctx := context.Background() // top-level: no deadline, no cancel
ctx = context.TODO() // placeholder when ctx not yet determined
// Derived contexts — ALWAYS defer cancel()
ctx1, cancel1 := context.WithCancel(context.Background())
defer cancel1() // prevents goroutine leak inside context machinery
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel2()
// Use in a worker goroutine
func fetchData(ctx context.Context, url string) ([]byte, error) {
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil { return nil, err } // err contains context.DeadlineExceeded
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
// Checking cancellation in a loop
func processItems(ctx context.Context, items []Item) error {
for _, item := range items {
select {
case <-ctx.Done(): // cancelled — stop early
return ctx.Err()
default: // continue
}
process(item)
}
return nil
}
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...
