Go Package context: Difference between revisions
Jump to navigation
Jump to search
Line 18: | Line 18: | ||
Function using context should accept it as their first argument. | Function using context should accept it as their first argument. | ||
</font> | </font> | ||
=TODO= | =TODO= | ||
* https://go.dev/blog/context | * https://go.dev/blog/context |
Revision as of 20:42, 8 February 2024
External
Internal
Overview
One of the key differences between Go and other language is explicit context propagation. Context propagation is a mechanism of propagating an additional call argument, called context, into function calls. There is actually a type called context.Context
.
The context is used for:
- Cancellation logic. You can pass a special instance of a context that can get canceled. In that case, all functions you were to call with it would be able to detect this. Can be useful for handling application shutdown or stopping any processing.
- Timeouts. Timeouts can be set for execution, by using the corresponding context functions.
- Propagating extra metadata. Additional key/value pairs can be propagate inside the context. Useful in distributed tracing. This feature should be used sparingly, in exceptional cases.
The context is immutable, but it can be cloned with extra metadata.
Function using context should accept it as their first argument.