title: How does defer and named return value work?
body: <p>I just started learning Go and I got confused with one example about using defer to change named return value in the <a href="https://blog.golang.org/defer-panic-and-recover" rel="noreferrer">The Go Blog - Defer, Panic, and Recover</a>.</p>
  <p>The example says:</p>
  <blockquote>
  <ol start="3">
  <li>Deferred functions may read and assign to the returning function's named return values.</li>
  </ol>
  <p>In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function <strong>returns 2</strong>:</p>
  </blockquote>
  <pre><code>func c() (i int) {
      defer func() { i++ }()
      return 1
  }
  </code></pre>
  <p>But as what I have learned from  <a href="https://tour.golang.org/basics/7" rel="noreferrer">A Tour of Go - Named return values</a></p>
  <blockquote>
  <p><strong>A return statement without arguments</strong> returns the named return values. This is known as a &quot;naked&quot; return.</p>
  </blockquote>
  <p>I tested in the following code and in function <code>b</code> it returns 1 because it wasn't the &quot;<em>A return statement without arguments</em>&quot; case mentioned above.</p>
  <pre><code>func a() (i int) { // return 2
      i = 2
      return
  }
  
  func b() (i int) {  // return 1 
      i = 2
      return 1
  }
  </code></pre>
  <p>So my question is in the first example, the surrounding function c has a named return value i, but the function <code>c</code> uses <code>return 1</code> which in the second example we can see it should have return 1 no matter what value <code>i</code> is. But why after <code>i</code> changes in the deferred function the <code>c</code> function returns the value of <code>i</code> instead the value 1?</p>
  <p>As I was typing my question, I might have guessed the answer. Is it because:</p>
  <pre><code>return 1 
  </code></pre>
  <p>is equals to:</p>
  <pre><code>i = 1
  return 
  </code></pre>
  <p>in a function with a named return value variable <code>i</code>?</p>
  <p>Please help me confirm, thanks!</p>