Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not that <code>()</code> must be added after (only) a <em>closure</em> in <code>defer</code>. The language specs for the <a href="http://golang.org/ref/spec#Defer_statements">defer statement</a> mandate that its 'Expression' <em>always</em> must be a function call.</p> <p>And why is it so? It's the same as with any other function, in 'defer' or not:</p> <p>Consider:</p> <pre><code>func f() int { return 42 } </code></pre> <p>and</p> <pre><code>a := f </code></pre> <p>vs</p> <pre><code>b := f() </code></pre> <p>The first expression RHS is a function value. In the second version the RHS is the value <em>returned by the function</em> - i.e. a function call.</p> <p>So is the semantics of:</p> <pre><code>defer f </code></pre> <p>vs</p> <pre><code>defer f() </code></pre> <p>except that the first version doesn't make sense in the context of 'defer', and so the specifications mention that it must be the second form (only).</p> <p>It's IMHO also easier to learn because of the orthogonality with the above discussed function call outside of the 'defer' statement.</p> <p>Also note that a function call is not only fn-expr followed by <code>()</code>, but an expression list is generally inside the parenthesis (including an empty list). There's a big difference between:</p> <pre><code>for i := range whatever { defer func() { fmt. Println(i) }() } </code></pre> <p>and </p> <pre><code>for i := range whatever { defer func(n int) { fmt. Println(n) }(i) } </code></pre> <p>The first version prints the value of 'i' in the moment when the closure <em>executes</em>, the second prints the value of 'i' in the moment when the defer statement <em>was</em> executed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload