Sobes.tech
Middle+

Как устроено наследование контекстов в Go (context.WithValue, context.Background)?

sobes.tech AI

Answer from AI

In Go, the context package implements a mechanism for passing execution context (such as timeouts, cancellations, values) between goroutines. Contexts are structured as a chain, where each new context is created based on a parent.

  • context.Background() is the root, empty context with no parent.
  • context.WithValue(parent, key, val) creates a new context that stores a key-value pair and references its parent.

When requesting a value via Value(key), the context first checks if it has this value; if not, it delegates the request to its parent, and so on up the chain. Thus, values are inherited through the context chain.

Example:

ctx := context.Background()
ctx1 := context.WithValue(ctx, "userID", 42)
ctx2 := context.WithValue(ctx1, "requestID", "abc123")

fmt.Println(ctx2.Value("userID"))    // 42
fmt.Println(ctx2.Value("requestID")) // abc123

Here, ctx2 inherits values from ctx1 and ctx.

Как устроено наследование контекстов в Go… - sobes.tech