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")
}$ go run defer.go
main operations
cleanup