Sobes.tech
Junior — Middle

Kas saaksid anda olukordi või juhtumeid, kus konteksti kontseptsiooni kasutatakse?

sobes.tech AI

Vastus AI-lt

In Go, the concept of context.Context is used to manage the lifecycle of operations, cancellations, timeouts, and passing values between goroutines.

Main use cases:

  • Cancel operations: for example, when working with network requests or databases, a long operation can be canceled if the client interrupts the request.
  • Timeouts and deadlines: you can set a maximum execution time for an operation, after which it will be automatically canceled.
  • Passing values: for example, request IDs, authentication tokens, metadata needed at different call levels.

Example:

func HandleRequest(ctx context.Context) {
    select {
    case <-time.After(5 * time.Second):
        // Perform work
    case <-ctx.Done():
        // Operation canceled or deadline exceeded
        return
    }
}

The context helps in writing more manageable and responsive code, especially in concurrent and network applications.