TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

More Gotchas of Defer in Go, Part II

105 pointsby inancgumusover 7 years ago

7 comments

jitlover 7 years ago
Also read the official blog post on defer: <a href="https:&#x2F;&#x2F;blog.golang.org&#x2F;defer-panic-and-recover" rel="nofollow">https:&#x2F;&#x2F;blog.golang.org&#x2F;defer-panic-and-recover</a><p>It covers about half of these gotchas by laying out how the defer statement works in plain English. The other half (like how closures work inside loops in Go) are covered elsewhere in the language tour.<p>I do really like the visualizations! Makes it very clear how these mechanics work.
评论 #15981155 未加载
评论 #15982125 未加载
brabelover 7 years ago
Every point mentioned was not a gotcha to anyone who read the official introductory tour of the language. The behaviour may be unexpected to newbies, but if you spent an hour or so learning the language, you shouldn&#x27;t be falling for these.
评论 #15983045 未加载
评论 #15982767 未加载
barellover 7 years ago
I think most of the people who understand the basic principles of how computers (and many languages) work wouldn’t be surprised by any of the „gotcha” described in this article. It seems to be written for people who just started working with golang without any or little knowledge about information technology.
评论 #15980894 未加载
评论 #15980843 未加载
评论 #15982565 未加载
brian-armstrongover 7 years ago
Defers just feel like a watered down version of what you get with good scoping and RAII. They&#x27;re a half measure for something programming languages solved decades ago.
评论 #15982585 未加载
knorkerover 7 years ago
#4 can also be fixed with:<p><pre><code> for i := 0; i &lt; 10; i++ { i := i &#x2F;&#x2F; Creates a *new* `i` defer func() { … something with i … } go func() { … something with i … } }</code></pre>
评论 #15981482 未加载
评论 #15983068 未加载
评论 #15981176 未加载
ramenmealover 7 years ago
I code in go every day professionally. These are not gotchas, they are well defined behaviors.
评论 #15986832 未加载
br1over 7 years ago
It&#x27;s indefensible that defer works on the function and not on the scope.
评论 #15982238 未加载
评论 #15981229 未加载