> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Go Defer Statement

The `defer` statement in Go schedules a function call to be executed immediately before the surrounding function returns. It pushes the deferred function call onto an internal stack, guaranteeing execution whether the surrounding function terminates normally (via a `return` statement) or abruptly (via a `panic`). However, deferred functions are **not** executed if the program terminates directly via `os.Exit()` or functions that call it internally (such as `log.Fatal()`).

```go theme={"dark"}
defer functionCall(arguments)
```

The behavior of `defer` is governed by three strict mechanical rules regarding evaluation, execution order, and return value interaction.

## 1. Immediate Argument Evaluation

The arguments passed to a deferred function are evaluated at the exact moment the `defer` statement is encountered during execution, not when the deferred function is eventually invoked.

```go theme={"dark"}
package main

import "fmt"

func main() {
    i := 0
    // The value of 'i' (0) is evaluated and saved here.
    defer fmt.Println(i) 
    i++
    // Prints 0, not 1.
}
```

*Note: If the deferred function is a method, the receiver is also evaluated immediately.*

## 2. LIFO Execution Order

When multiple `defer` statements are declared within the same function, they are pushed onto a call stack. Upon the surrounding function's return, these deferred calls are popped off the stack and executed in Last-In, First-Out (LIFO) order.

```go theme={"dark"}
package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        defer fmt.Print(i)
    }
    // Prints: 210
}
```

## 3. Interaction with Named Return Values

Deferred functions are executed *after* the surrounding function's `return` statement updates the return variables, but *before* the function actually yields control back to its caller. Consequently, a deferred anonymous function can read and modify the surrounding function's named return values.

```go theme={"dark"}
package main

import "fmt"

func modifyReturn() (result int) {
    defer func() {
        // Modifies the named return value after the return statement executes
        result *= 2 
    }()
    return 5 // result is set to 5, then deferred function runs, changing result to 10
}

func main() {
    fmt.Println(modifyReturn()) // Prints: 10
}
```

## Scope and Memory Considerations

A critical technical distinction in Go is that `defer` is bound to **function scope**, not block scope.

If a `defer` statement is placed inside a nested lexical block (such as a `for` loop), the deferred function will not execute when the block terminates. It will only execute when the parent function returns.

```go theme={"dark"}
package main

import "fmt"

func main() {
    for i := 0; i < 10000; i++ {
        // WARNING: These are pushed to the function's defer stack 10,000 times.
        // They do not execute at the end of each loop iteration.
        defer fmt.Sprint(i) 
    }
    // All 10,000 deferred calls execute here, right before main returns.
}
```

Because the defer stack allocates memory for each deferred call and its evaluated arguments, placing `defer` inside unbounded or large loops can lead to excessive memory consumption or stack overflows. To force block-level defer execution, the block must be wrapped in an anonymous function (or closure) that is invoked immediately.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Go Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
