defer in Golang

defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages.

Example:

func main() {
	defer fmt.Println("cleanup")
	fmt.Println("main operations")
}
defer will be executed at the end of the enclosing function main, after main operations has finished.

Output:
$ go run defer.go
main operations
cleanup