from Hacker News

More Gotchas of Defer in Go, Part II

by inancgumus on 12/21/17, 4:02 PM with 53 comments

  • by jitl on 12/21/17, 5:10 PM

    Also read the official blog post on defer: https://blog.golang.org/defer-panic-and-recover

    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.

    I do really like the visualizations! Makes it very clear how these mechanics work.

  • by brabel on 12/21/17, 5:03 PM

    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't be falling for these.
  • by barell on 12/21/17, 5:21 PM

    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.
  • by brian-armstrong on 12/21/17, 8:38 PM

    Defers just feel like a watered down version of what you get with good scoping and RAII. They're a half measure for something programming languages solved decades ago.
  • by knorker on 12/21/17, 5:22 PM

    #4 can also be fixed with:

        for i := 0; i < 10; i++ {
          i := i  // Creates a *new* `i`
          defer func() { … something with i … }
          go func() { … something with i … }
        }
  • by ramenmeal on 12/22/17, 6:42 AM

    I code in go every day professionally. These are not gotchas, they are well defined behaviors.
  • by br1 on 12/21/17, 5:45 PM

    It's indefensible that defer works on the function and not on the scope.