Junior — Middle
How to organize the sequence of executing multiple deferred tasks?
sobes.tech AI
Answer from AI
In Go, the keyword defer is used to schedule a function call to be executed when the current function exits. To organize the sequence of multiple deferred tasks, it is important to remember that defer calls are executed in the reverse order of their declaration (stack).
Example:
def func() {
defer fmt.Println("First")
defer fmt.Println("Second")
defer fmt.Println("Third")
fmt.Println("Executing function")
}
The output will be:
Executing function
Third
Second
First
If you need the deferred tasks to execute in the same order as they are declared, you can use an explicit stack or list and execute them manually, or avoid using defer for such cases.