What is the defer statement in Go?

Answer

The defer statement schedules a function call to be executed just before the surrounding function returns, regardless of whether it returns normally or panics. Deferred calls are stacked in LIFO (last-in, first-out) order — the last defer in a function runs first. It is the idiomatic Go way to handle cleanup: defer file.Close(), defer mutex.Unlock(), defer rows.Close(). Because deferred calls run even when a panic occurs (combined with recover), they are also used for cleanup during error recovery.