context.TODO() vs. context.Background()
suggest changeYou 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, emptyContext
. Code should usecontext.TODO
when it’s unclear whichContext
to use or it is not yet available (because the surrounding function has not yet been extended to accept aContext
parameter).TODO
is recognized by static analysis tools that determine whetherContexts
are propagated correctly in a program.
And context.Background()
as:
Background
returns a non-nil, emptyContext
. 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-levelContext
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents