Sobes.tech
Middle

What is defer and what is it used for? In what order are defer calls executed if there are several in one function?

sobes.tech AI

Answer from AI

In Go, the keyword defer is used to schedule a function call to be executed after the surrounding function completes, but before it returns. This is useful for resource cleanup, closing files, unlocking mutexes, and other cleanup operations.

If there are multiple defer calls in a function, they are executed in the reverse order of their declaration (stack order). That is, the last declared defer will be executed first.

Example:

func example() {
    defer fmt.Println("First defer")
    defer fmt.Println("Second defer")
    fmt.Println("Inside the function")
}
// Output will be:
// Inside the function
// Second defer
// First defer