What is Context in Go: Simple Explanation and Usage
Context in Go is a way to carry deadlines, cancellation signals, and request-scoped values across API boundaries and goroutines. It helps manage the lifecycle of processes, especially in concurrent programming, by allowing you to stop work early or pass data safely.How It Works
Think of context as a messenger that travels with your tasks in Go programs. It carries important signals like when to stop working (cancellation) or when a deadline is reached. This messenger can also hold small pieces of information that only apply to that task.
When you start a task, you create a context object. If you want to stop the task early, you can cancel the context, and all parts of the program listening to it will know to stop too. This is very useful when you have many tasks running at once and want to avoid wasting resources.
Contexts are passed explicitly to functions, so everyone involved knows about the task's state. This is like passing a shared note that says "stop now" or "deadline reached" to all helpers working on the job.
Example
This example shows how to create a context with a timeout and how a goroutine listens for cancellation to stop work early.
package main import ( "context" "fmt" "time" ) func doWork(ctx context.Context) { for { select { case <-ctx.Done(): fmt.Println("Work stopped:", ctx.Err()) return default: fmt.Println("Working...") time.Sleep(500 * time.Millisecond) } } } func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() go doWork(ctx) // Wait for the context to be done <-ctx.Done() }
When to Use
Use context in Go when you need to control how long a task runs or when you want to stop it early. It is especially helpful in web servers, API calls, or any program with multiple goroutines working together.
For example, if a user cancels a web request, the server can use context to stop processing that request immediately. It also helps pass request-specific data like user IDs safely between functions without using global variables.
Key Points
- Context carries cancellation signals and deadlines.
- It helps stop work early to save resources.
- Pass context explicitly to functions to share task state.
- Use it to pass request-scoped values safely.
- Commonly used in concurrent and networked Go programs.