Member-only story
Mastering Context Usage in Go: A Comprehensive Guide
Introduction
In everyday development, the use of context is inevitable. For instance, when working with packages like mongodb-driver, the Find method is commonly employed:
func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (cur *Cursor, err error) {
// Implementation...
}
While it’s common to use context.Background()
, the question arises: why might one use context.TODO()
in this context? Let's delve into the differences between context.Background()
and context.TODO()
.
Differences Between context.Background()
and context.TODO()
Let’s examine their code implementations; essentially, they are identical.
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)
// Background returns a non-nil, empty Context. It is never canceled, has no values,
// and has no deadline. It is typically used by the main function, initialization,
// and tests, and as the top-level Context for incoming requests.
func Background() Context {
return background
}
// TODO returns a non-nil, empty Context. Code should use context.TODO when it's
// unclear which Context to use or it is not yet available (because the surrounding
// function has not yet been extended to accept a Context parameter).
func TODO() Context {
return todo
}
From the comments, we gather that both context.Background()
and context.TODO()
are used to create a…