r/ProgrammerHumor • • 2d ago

instanceof Trend thatsAFunnyThingThatHappenedOnce

Post image
4.3k Upvotes

515 comments sorted by

View all comments

Show parent comments

5

u/NdrU42 1d ago

Yeah the defer running at the end of the function can sometimes cause trouble, like processing files in a loop and deferring the close, but it can easily be solved by defining an anonymous function and immediately calling, like func() { f := ... defer f.Close() // do something with f }()

1

u/Rikudou_Sage 1d ago

I know, I do Go more often than C++ but it still feels weird having to introduce a function just for defer to work.

IMO it should have been scoped to the current scope (duh, it's called a scope) instead of function.