The defer statement schedules a function call to run when the current function returns. It's commonly used for cleanup:
func readFile() {
file := open("data.txt")
defer file.Close() // runs when function returns
// work with file...
}
No matter how the function exits, the deferred call runs. This guarantees cleanup even if an error occurs partway through. Put defer right after acquiring a resource.