# 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>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.codewithgo.com/defer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
