The context Package

Let’s learn about the Context type and the context package.

Purpose of the context package

The main purpose of the context package is to define the Context type and support cancellation. Yes, you heard that right; there are times when, for some reason, we want to abandon what we are doing. However, it would be very helpful to be able to include some extra information about our cancellation decisions. The context package allows us to do exactly that.

If we take a look at the source code of the context package, we will realize that its implementation is pretty simple—even the implementation of the Context type is pretty simple, yet the context package is very important.

The Context type is an interface with four methods named Deadline(), Done(), Err(), and Value(). The good news is that we do not need to implement all of these functions of the Context interface—we just need to modify a Context variable using methods such as context.WithCancel(), context.WithDeadline(), and context.WithTimeout().

Note: All three of these functions return a derived Context (the child) and a CancelFunc() function. Calling the CancelFunc() function removes the parent’s reference to the child and stops any associated timers. As a side effect, this means that the Go garbage collector is free to garbage collect the child goroutines that no longer have associated parent goroutines. For garbage collection to work correctly, the parent goroutine needs to keep a reference to each child goroutine. If a child goroutine ends without the parent knowing about it, then a memory leak occurs until the parent is canceled as well.

Coding example

The example that follows showcases the use of the context package. The program contains four functions, including the main() function. Functions f1(), f2(), and f3() each require just one parameter, which is a time delay because everything else they need is defined inside their function body. In this example, we use context.Background() to initialize an empty Context. The other function that can create an empty Context is context.TODO(), which is presented later on in this chapter.

Get hands-on with 1200+ tech skills courses.