Sobes.tech
Middle+

Why pass the context as the first argument in Go?

sobes.tech AI

Answer from AI

In Go, context is passed as the first argument to functions and methods to provide a unified way to manage the request's lifecycle, cancellation, and metadata passing.

Main reasons:

  • Operation cancellation: allows canceling long-running or hanging operations, for example, when closing an HTTP request.
  • Timeouts and deadlines: you can set a limit on execution time.
  • Data passing: through context, information can be transmitted, such as request identifiers for logging.

The standard is that context.Context is always the first parameter, making it clear that the function supports context management.

Example:

func ProcessRequest(ctx context.Context, data string) error {
    select {
    case <-time.After(5 * time.Second):
        // processing
        return nil
    case <-ctx.Done():
        return ctx.Err() // cancellation or timeout
    }
}

This approach improves control over execution and simplifies operation cancellation in complex systems.