Middle
Millises järjekorras täidetakse Go-s delegeeritud funktsioonid (defer)?
sobes.tech AI
Vastus AI-lt
Deferred functions are executed in the reverse order of their declaration, i.e., LIFO (Last-In, First-Out).
package main
import "fmt"
func main() {
defer fmt.Println("first") // Declared last
defer fmt.Println("second") // Declared before last
defer fmt.Println("third") // Declared first
}
As a result, when this code runs, it will output:
third
second
first
When exiting the scope (function) where defer was declared, the deferred functions are called in reverse order. This is useful for releasing resources, closing files, unlocking mutexes, and other cleanup operations.