context.TODO() vs. 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
TODOreturns a non-nil, empty
Context. Code should use
context.TODOwhen it’s unclear which
Contextto use or it is not yet available (because the surrounding function has not yet been extended to accept a
TODOis recognized by static analysis tools that determine whether
Contextsare propagated correctly in a program.
Backgroundreturns 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
Contextfor incoming requests.
Frankly, I’m not sure what they are trying to say.
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.