The example above uses various concepts learned in the blog. First, the main
function creates a context and passes it to the processOrder
function in line 11, and we can see that the context is passed to other functions in the call chain. It is important to remember that with context.WithCancel
, only the function creating the context can use the cancel
function to cancel the context and any contexts derived from it.
We have used time.Sleep
to simulate processing, and for our case, the main
function cancels the context in line 17, while the inventory details are being fetched. When a context is passed to a function, it should honor it by checking for its cancelation. There is a more elegant way to handle this by using select
, channels
, and a separate goroutine to concurrently poll for the cancel message. We leave this as an exercise for you!
Summary#
The context
package allows for the functions to have more context about the environment they are running in. The use cases for the Go context
package include efficiently handling cancelations, timeouts, and passing data between goroutines. Contexts can be created and derived from existing contexts, resulting in a tree-like hierarchical structure.
Context is commonly used in environments where concurrent operations’ life cycle management and cancelation are crucial, such as distributed systems. We encourage you further to enrich your knowledge and understanding of the Go language. For Go interview prep, you can follow the path below.