Sobes.tech
Middle

How does context inheritance work in Go?

sobes.tech AI

Answer from AI

In Go, contexts (context.Context) are designed so that you can create a hierarchy of contexts, where a child context inherits values and cancellation from its parent.

When a new context is created based on a parent (for example, through context.WithCancel, context.WithTimeout, or context.WithValue), it "inherits" the state of the parent:

  • If the parent context is canceled, all its children are automatically canceled as well.
  • Values stored in the parent context are accessible to children unless they are overridden.

Thus, context inheritance allows for convenient management of operation lifetimes and data passing through call chains.

Example:

parentCtx := context.Background()
ctx, cancel := context.WithCancel(parentCtx)

// ctx inherits from parentCtx

// If cancel() is called, ctx and all its descendants will be canceled

// You can also create child contexts from ctx, and cancellation will propagate downward
How does context inheritance work in Go? — Golang - sobes.tech