Junior — Middle
What additional functions and methods were introduced in the context package in Go 1.21?
sobes.tech AI
Answer from AI
In the Go 1.21 release, several new functions and methods were added to the context package, aimed at improving working with contexts and managing the lifetime of operations.
The main innovations include:
- Functions for convenient creation of contexts with timeouts and deadlines.
- Methods for more flexible management of context cancellation and value passing.
- Improvements in performance and security when working with contexts.
For example, a new function context.WithDeadlineFunc was introduced, which allows setting a function to be called upon reaching a deadline.
ctx, cancel := context.WithDeadlineFunc(parentCtx, deadline, func() {
fmt.Println("Deadline reached")
})
defer cancel()
These additions make working with contexts more convenient and allow better control over the lifecycle of operations in Go applications.