How defer Works
Run code at scope exit regardless of path.
What defer Does
A defer block schedules code to run when the current scope is about to exit, no matter how it exits.
func demo() {
defer { print("cleanup") }
print("work")
}
demo()Runs at Scope Exit
The deferred code runs after the rest of the scope finishes, just before control leaves it.
func greet() {
defer { print("goodbye") }
print("hello")
}
greet()