Getting started
Basic types
Variables
Constants
Strings
Pointers
Arrays
Slices
Maps
Structs
Interfaces
Empty interface
if, switch, goto
for, while loops
range statement
Functions
Methods
Error handling
Defer
Panic and recover
Concurrency
Channels and select
Mutex
Packages
Files and I/O
Time and date
Command line arguments
Logging
Executing commands
Hex, base64 encoding
JSON
XML
CSV
YAML
SQL
HTTP Client
HTTP Server
Text and HTML templates
Reflection
Context
Creating a context
Using context with timeout to set timeout for HTTP requests
Context with value
Writing cancellable functions
Context is a tree of values
context.TODO() vs. context.Background()
Package fmt
OS Signals
Testing
Calling C from GO with cgo
Profiling using go tool pprof
Cross compilation
Conditional compilation with build tags
Inlining functions
sync.Pool for better performance
gob
Plugin
HTTP server middleware
Protobuf in Go
Console I/O
Cryptography
Images (PNG, JPEG, BMP, TIFF, WEBP, VP8, GIF)
The Go Command
Testing code with CI services
Windows GUI programming
Contributors

context.TODO() vs. context.Background()

suggest change

You can create new, empty context using context.TODO() and context.Background().

What’s the difference?

In terms of functionality: none. They are exactly the same value, bit-by-bit.

The difference is in intent.

Official documentation describes context.TODO() as:

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). TODO is recognized by static analysis tools that determine whether Contexts are propagated correctly in a program.

And context.Background() as:

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.

Frankly, I’m not sure what they are trying to say.

I guess context.TODO() is meant to be used if you expect that at some point in the future you’ll no longer need to create context there, either because it’ll be passed from the outside or that there will be a more specific way to create it.

If you can’t decide, don’t sweat it. In practice they behave the same way so pick whichever.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents