Sobes.tech
Junior — Middle

Is it possible to have multiple defer operators inside one function?

sobes.tech AI

Answer from AI

Yes, in Go, you can use multiple defer statements within a single function. All deferred calls will be executed in reverse order (LIFO) after the function completes. This is convenient for releasing resources, closing files, unlocking mutexes, etc.

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
Is it possible to have multiple defer operators… - sobes.tech