Senior
What do you know about working with context in Go? What methods does it have?
sobes.tech AI
Answer from AI
In Go, the context package is used for passing cancellation signals, deadlines, and other values between goroutines, especially in network and asynchronous operations.
Main methods and functions:
context.Background()— returns an empty context, usually used as the root.context.TODO()— a placeholder when the context is not yet defined.WithCancel(parent Context)— returns a new context and a cancel function, allowing to cancel operations.WithDeadline(parent Context, deadline time.Time)— creates a context with a deadline.WithTimeout(parent Context, timeout time.Duration)— creates a context with a timeout.WithValue(parent Context, key, val interface{})— creates a context with an attached value.
Example usage:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("operation finished")
case <-ctx.Done():
fmt.Println("operation canceled or timed out")
}
Context helps control the lifetime of operations and pass parameters without global variables.