> For the complete documentation index, see [llms.txt](https://book.codewithgo.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.codewithgo.com/defer.md).

# 25. Defer

### Defer Statement

`defer` is special keyword in Go to schedule some action until function returns. Defer is mostly used in cleanup task that should be done when returning from a function. Defer find its use similar to what finally does in some programming languages. Semantic for defer is&#x20;

`defer some_action`

{% code title="main.go" %}

```go
func sayHello() {

	defer fmt.Println("Performing cleanup")
	fmt.Println("Hello, There!")

}
func main() {
	sayHello()
}
```

{% endcode %}

Here, call to print cleanup is scheduled to be executed when function returns. Hello, There is printed first and then Performing cleanup.

### Panic scenarios

The benefit of using `defer` keyword is that Go guarantees it will be carried out even if there is panic.

{% code title="main.go" %}

```go
func doPanic() {
	defer fmt.Println("Performing cleanup")
	panic("Oops")
	fmt.Println("Hello, There")
}
func main() {
	doPanic()
}
```

{% endcode %}

In this case, defer will still print Performing cleanup.

### Blog Posts

{% embed url="<https://blog.learngoprogramming.com/gotchas-of-defer-in-go-1-8d070894cb01>" %}

{% embed url="<https://blog.learngoprogramming.com/5-gotchas-of-defer-in-go-golang-part-ii-cc550f6ad9aa>" %}

{% embed url="<https://blog.golang.org/defer-panic-and-recover>" %}
