←back to thread

Go is still not good

(blog.habets.se)
644 points ustad | 2 comments | | HN request time: 0s | source
Show context
torginus ◴[] No.44983258[source]
I still don't understand why defer works on function scope, and not lexical scope, and nobody has been able to explain to me the reason for it.

In fact this was so surprising to me is that I only found out about it when I wrote code that processed files in a loop, and it started crashing once the list of files got too big, because defer didnt close the handles until the function returned.

When I asked some other Go programmers, they told me to wrap the loop body in an anonymus func and invoke that.

Other than that (and some other niggles), I find Go a pleasant, compact language, with an efficient syntax, that kind of doesn't really encourage people trying to be cute. I started my Go journey rewriting a fairly substantial C# project, and was surprised to learn that despite it having like 10% of the features of C#, the code ended up being smaller. It also encourages performant defaults, like not forcing GC allocation at every turn, very good and built-in support for codegen for stuff like serialization, and no insistence to 'eat the world' like C# does with stuff like ORMs that showcase you can write C# instead of SQL for RDBMS and doing GRPC by annotating C# objects. In Go, you do SQL by writing SQL, and you od GRPC by writing protobuf specs.

replies(7): >>44983266 #>>44983314 #>>44983343 #>>44983484 #>>44984652 #>>44985794 #>>44992509 #
grey-area ◴[] No.44983266[source]
There’s probably no deep reason, does it matter much?
replies(2): >>44983739 #>>44985389 #
1. torginus ◴[] No.44983739[source]
Yes it does, function-scope defer needs a dynamic data structure to keep track of pending defers, so its not zero cost.

It can be also a source of bugs where you hang onto something for longer than intended - considering there's no indication of something that might block in Go, you can acquire a mutex, defer the release, and be surprised when some function call ends up blocking, and your whole program hangs for a second.

replies(1): >>44985567 #
2. nasretdinov ◴[] No.44985567[source]
I think it's only a real issue when you're coming from a language that has different rules. Block-scoping (and thus not being able to e.g. conditionally remove a temp file at the end of a function) would be equally surprising for someone coming from Go.

But I do definitely agree that the dynamic nature of defer and it not being block-scoped is probably not the best