Go for C# developers: defer is not IDisposable

When using an IDisposable object in C# you have some pretty clear expectations on when that object is disposed. While the same thing is technically true with defer in Go, I've seen a lot of people misunderstand when exactly the deferred method is called.

In C# we expect the Dispose method to pretty much be called when the disposable object goes out of scope. Unless you use a using statement you technically don't have a guarantee, but there is always a chance that your object gets disposed pretty soon after it goes out of scope due to the garbage collector.

In Go however when you use the defer to mimic disposing of an object, the deferred method is not executed until the method returns. This is an important difference. You are actually guaranteed it will not be executed until the method returns.

I have seen this cause confusion and problems when people use defer inside a loop since all cleanup functionality is postponed until after the method where the loop resides returns. And the way to fix it is to create a new function that actually returns for each iteration in the loop. Here is an example showing both the "wrong" and "right" way to have a deferred method execute for each iteration in a loop.

No comments:

Post a Comment