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 }
More Related questions...