Junior — Middle
Kuidas eristada Context.TODO kasutamist Context.Background-st koodis ja millistel juhtudel neid funktsioone kasutatakse?
sobes.tech AI
Vastus AI-lt
In Go, context.Background() and context.TODO() return a context, but they are used in different situations:
-
context.Background()— is the base, empty context, which is usually used as the root context in main functions, tests, or during initialization. It means the context is not canceled and contains no values. -
context.TODO()— is used as a placeholder in places where the context is not yet defined or it has not been decided which context to use. It signals to developers that they should think about it later and replace it with an appropriate context.
Example:
func main() {
ctx := context.Background() // root context
process(ctx)
}
func process(ctx context.Context) {
// if we don't yet know which context to pass further
childCtx := context.TODO()
doSomething(childCtx)
}
Summary:
- Use
Background()as the root context. - Use
TODO()as a temporary placeholder when the context is not yet defined.