How Defer works in Go Lang and how execution stack and thread of execution behaves?

How Defer works in Go Lang - I observed that defer function executes even after the return statement of the caller function so the question is how it works at the backend, how the execution stack behaves?

If defer function can access the data of the caller function that means defer function forms the closure with the caller function or GC stores the data which is defined in the caller function and also getting used by defer function on the heap. Go program first put caller function onto the stack and start executing code inside caller function and when caller function found defer statement, it will push defer function call to the stack and continue to execute next lines of codes. Once the caller function is done with the execution of all code except defer function call, the thread of execution will start executing defer function calls in LIFO order, and once all defer functions are executed and pop up from the stack, the caller function is also get pop-up from the stack.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.