DEV Community

Cover image for Let's Chat About Contexts in Go
Talina
Talina

Posted on

Let's Chat About Contexts in Go

Today I want to have a brief chat about Contexts in Go. :)

Every Go developer uses Contexts in their coding lifetime.

Read this profound yet straightforward blog if you are new to Go and Contexts.

To excel as a developer, we should actively make an effort to understand the "why".

There are many great articles on the web about using Contexts in Go and the how-to.

But, let's mull over why should Contexts be used in the first place.


Carriers of Metadata

Contexts carry miscellaneous metadata that is helpful for each invoked function call. This metadata could include the caller's information or general identification information.

This metadata is also helpful while debugging incoming requests if we log the messages with the context information.

Resources Saver!

Contexts offer an ability to cancel an ongoing operation if -

  • The caller invoked a cancellation -

    • Imagine a scene where a flick to the first domino makes all subsequent dominos fall.
    • That is how the parent Context's CancelFunc cancels derived contexts.
  • When the operation takes longer than expected -

    • In this case, the Context's cancel logic is invoked when the configured deadline exceeds, and this cancellation propagates to the derived contexts.

The advantage of context cancellation is that all goroutines exit immediately, and the application can reclaim used resources such as memory.

Using Contexts is a way to safeguard resource consumption.


Further Reading

If you want to understand Contexts in-depth, I recommend you head over to these links -

Contexts and Structs

This blog advocates a noteworthy takeaway -

Context makes it easy to propagate important cross-library and cross-API information down a calling stack. But, it must be used consistently and clearly in order to remain comprehensible, easy to debug, and effective.

Context Pkg

For the How-To.

Until Later!

Top comments (0)