A very convenient keyword in Go is defer which allows you to defer the execution of a function until the surrounding function returns. I was curious to know how Golang implements it, and here’s what I found 👇
When we define a defer function it is attached to the current goroutine; and when there are multiple defer functions they form a linked list through the “link” attribute.
This entire arrangement forms a logical stack ⚡ and this is why when you define multiple defer functions, they get executed in the reverse order of definition.
This a classic example of implementing stack using a linked list 😅
If you are interested in digging deeper, here’s the link to the source code. https://lnkd.in/gpUyvN8x
Going through the programming language internals makes you realize the importance of data structures and performance optimizations. Every single line of code matters.
⚡ I keep writing and sharing my practical experience and learnings every day, so if you resonate then follow along. I keep it no fluff.
youtube.com/c/ArpitBhayani