Common traps while using defer in go

Aniruddha
Aniruddha
Mar 20, 2018 · 3 min read

The defer statement in go is really handy in improving code readability. However, in some cases its behavior is confusing and not immediately obvious. Even after writing go for over 2 years, there are times when a defer in the wild leaves me scratching my head. My goal is to compile a list of behaviors which have stumped me in the past, mainly as a note to myself.

Defer scopes to a function, not a block

A variable exists only within the scope of a code block. However, a defer statement within a block is only executed when the enclosing function returns. I’m not sure what the rationale for this is, but it can catch you off guard if you’re, say, allocating resources in a loop but defer the deallocation.

Chaining methods

If you chain methods in a defer statement, everything except the last function will be evaluated at call time. defer expects a function as the “argument”.

Prints —

The Logger() function is called before any of the work in do() is executed.

Function arguments

Okay, but what if the last method in the chain takes an argument? Surely, if it is executed after the enclosing function returns, any changes made to the variables will be captured.

Guess what this prints?

The value of err is captured at call time. Any changes made to this variable are not captured by the defer statement because they don’t point to the same value.

Calling methods on non-pointer types

We saw how chained methods behave in a defer statement. Exploring this further, if the called method is not defined on a pointer receiver type, calling it in a defer will actually make a copy of the instance.

This prints —

m is copied when defer is called. m.Foo() is basically shorthand for Foo(m)

Conclusion

If you’ve spent enough time writing go, these might not feel like “traps”. But for someone new to the language, there are definitely a lot of places where the defer statement does not satisfy the principle of least astonishment. There are a bunch of other places that go into more detail about some other common mistakes while writing go. Do check them out.

i0exception

Wut?

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store