programming

Getting to Know Package Context in Golang

Introduction to package context

Context is a package that can store and carry data values, timeout signals and deadline signals. This context runs and is created per request. The context usually carries the value from initialization until the end of the process. This context is sometimes a necessity when we code a program so that from the beginning of the function to the next function the previous value can be used if the process in the next function requires data from the initial process.

Why should we use context?

Useful for sending a value into a signal, and continuing to the next stages or functions by carrying the value from start to finish. Apart from that, we can also cancel the desired process so that all subsequent processes will be canceled by sending an abort signal.

Context adheres to the concept of parent and child processes, where if we create a context, we can also create child contexts from existing ones, even in one parent context there can be many child contexts. However, in a child context there is only one parent context. We understand this concept the same as inheritance which is usually explained in object-oriented programming.

Context is also an immutable object, where once the context is created it cannot be changed again. So if we add or change a context, the context will automatically create a new child instead of changing the context.

Method Usage

The context in Golang is in the form of an interface, so we need a struct that matches the contract in the interface. But don’t worry, Golang has provided several functions that we can use to create context.

FunctionUses
context.Background()makes the default context empty, has no cancellation, no timeout, and has no value. Usually used for the beginning of the initialization process.
context.TODO()creating a context is the same as background but we don’t know what we want yet

Implementation and samples

In its implementation, the difference between context.Background() and context.TODO() is not that different, it’s just that the information carried has different values when the context is initialized.

func main() {
	background := context.Background()
	fmt.Println(background)

	todo := context.TODO()
	fmt.Println(todo)
}

The following are the results when we run the program above.

✗ go run app.go
context.Background
context.TODO

Conclusion

Context can help us to trace the program that we have created because later we must send this context as a param to each function so that each function stores data and can also get data from previous functions that were passed by the process of the program. In the next session we will discuss how to implement it in more depth so that we really understand why we need to implement this context when coding in the Golang language.

comments powered by Disqus