title: Is golang defer statement execute before or after return statement?
body: <p>I have a question about golang defer: <strong>Is golang defer statement execute before or after return statement?</strong></p>
  
  <p>I have read <a href="https://golang.org/ref/spec#Defer_statements" rel="noreferrer">Defer_statements</a>. But I do not got the answer.</p>
  
  <p>I made a simple test:</p>
  
  <pre><code>func test1() (x int) {
      defer fmt.Printf("in defer: x = %d\n", x)
  
      x = 7
      return 9
  }
  
  func test2() (x int) {
      defer func() {
          fmt.Printf("in defer: x = %d\n", x)
      }()
  
      x = 7
      return 9
  }
  
  func test3() (x int) {
      x = 7
      defer fmt.Printf("in defer: x = %d\n", x)
      return 9
  }
  
  func main() {
      fmt.Println("test1")
      fmt.Printf("in main: x = %d\n", test1())
      fmt.Println("test2")
      fmt.Printf("in main: x = %d\n", test2())
      fmt.Println("test3")
      fmt.Printf("in main: x = %d\n", test3())
  }
  </code></pre>
  
  <p>In <code>test1()</code>, using <code>Printf</code>to print x after defer.
  In <code>test2()</code>, using a anonymous function to print x after defer.
  In <code>test3()</code>, using <code>Printf</code>to print x after defer, but defer after <code>x = 7</code>.</p>
  
  <p>But the result is:</p>
  
  <pre><code>test1
  in defer: x = 0
  in main: x = 9
  test2
  in defer: x = 9
  in main: x = 9
  test3
  in defer: x = 7
  in main: x = 9
  </code></pre>
  
  <p>So, is any one can explain:
  1. why got this result? why test1 prints 0, test2 print9, test3 prints 7.
  2. is defer statement excutes after return or before return?</p>
  
  <p>Thanks a lot.</p>