Introduction
Defer lets you delay running a piece of code until the surrounding function finishes. It helps clean up resources in the right order.
Defer lets you delay running a piece of code until the surrounding function finishes. It helps clean up resources in the right order.
defer functionCall()
Deferred calls run just before the function returns.
If you defer multiple calls, they run in last-in, first-out order.
defer fmt.Println("First") defer fmt.Println("Second") fmt.Println("Third")
file, _ := os.Open("file.txt")
defer file.Close()This program shows that deferred calls run after the main function finishes, in reverse order of defer statements.
package main import "fmt" func main() { defer fmt.Println("First deferred") defer fmt.Println("Second deferred") fmt.Println("Function body") }
Deferred functions run even if the function panics.
Arguments to deferred functions are evaluated immediately, but the call happens later.
Use defer to delay code until a function ends.
Deferred calls run in reverse order.
Great for cleanup tasks like closing files or unlocking.
defer statements are used in a Go function?defer is followed directly by the function call without assignment or parentheses around defer.defer fmt.Println("Hello"). Other options misuse defer syntax.package main
import "fmt"
func main() {
defer fmt.Println("First")
defer fmt.Println("Second")
fmt.Println("Third")
}func example() {
defer fmt.Println("A")
defer fmt.Println("B")
defer fmt.Println("C")
fmt.Println("D")
}
If the output is not as expected, what is the likely mistake?Pass the test and this pattern moves unknown