đ§ How Closures Work Under the Hood in Go.

A self-motivated and enthusiastic web developer with a deep interest in JavaScript (React.js). To work in the Software industry with modern web technologies of different local & multinational Software/ IT agencies of Bangladesh and grow rapidly with increasing responsibilities.
đ§Š Go Closures āĻāϰ āĻāĻŋāϤāϰā§āϰ āĻāĻžāĻ â Struct, Heap Allocation & Memory Management
Go āϤ⧠closure āĻŽāĻžāύā§āĻ āĻļā§āϧ⧠āĻāĻāĻāĻž anonymous function āύ⧠â āĻāϰ āϏāĻžāĻĨā§ āĻĨāĻžāĻā§ āĻāĻāĻāĻž hidden struct, āϝāĻž captured variables āϧāϰ⧠āϰāĻžāĻā§āĨ¤
āĻāĻ āĻāĻŽāĻŋ Go closure āĻāϰ under-the-hood memory behavior āύāĻŋā§ā§ āĻŦāĻŋāϏā§āϤāĻžāϰāĻŋāϤ āĻāϞā§āĻāύāĻž āĻāϰāĻŦ āĨ¤
đš āϏāĻžāϧāĻžāϰāĻŖ Go Closure āĻāĻĻāĻžāĻšāϰāĻŖ:
func multiplier(factor int) func(int) int {
return func(n int) int {
return n * factor
}
}
āĻāĻāĻžāύ⧠factor closure āĻāϰ āĻāĻŋāϤāϰ captured āĻšā§ā§āĻā§āĨ¤ āϤāĻžāϰ āĻŽāĻžāύ⧠factor āĻāϰ value ke closure āĻšāĻŋāϏā§āĻŦā§ āϰā§āĻā§ āĻĻāĻŋāϤ⧠āĻšāĻŦā§ āϝāĻžāϤ⧠, stack Frame āĻĨā§āĻā§ multiplier function āĻāϞ⧠āĻā§āϞ⧠factor āĻāϰ āĻā§āϝāĻžāϞ⧠āύāĻž āĻšāĻžāϰāĻŋā§ā§ āϝāĻžā§ āĨ¤
āĻāĻŦāĻžāϰ āĻāϏā§āύ āĻĻā§āĻāĻŋ ,
đ Go Under the Hood āĻāĻŋ āĻāϰā§?
- āϝāĻāύ āĻāĻŽāϰāĻž go run build āĻāϰāĻŋ āĨ¤ Go compiler automatic āĻāĻžāĻŦā§ āĻāĻāĻāĻž hidden struct āϤā§āϰāĻŋ āĻāϰā§, āϝāĻž closure captured variables āϰāĻžāĻā§, āϝā§āĻŽāύ:
type multiplierEnv struct {
factor int
}
func (e *multiplierEnv) closure(n int) int {
return n * e.factor
}
āϝāĻāύ closure stack frame āĻāϰ āĻŦāĻžāĻāϰ⧠āϝāĻžā§ (e.g. return āĻšā§), āϤāĻāύ Go āĻāϰ escape analysis āĻāϰ⧠āĻŦāϞ⧠āϝ⧠āĻāĻ struct āĻāĻŋ heap āĻ allocate āĻāϰāϤ⧠āĻšāĻŦā§āĨ¤
āĻ āϰā§āĻĨāĻžā§ captured variables āĻāϰ stack āĻ āĻĨāĻžāĻā§ āύāĻž, āĻŦāϰāĻ heap āĻ āĻāϞ⧠āϝāĻžā§, āϝāĻžāϤ⧠closure function lifetime āϝāϤāĻĻāĻŋāύ āĻĨāĻžāĻā§, variables āĻ āϤāϤ āϏāĻŽā§ āĻŦā§āĻā§ āĻĨāĻžāĻā§āĨ¤
đĄ Escape Analysis āύāĻŋāĻļā§āĻāĻŋāϤ āĻāϰāϤā§:
go build -gcflags="-m" main.go
Output āĻ āĻĻā§āĻāĻŦā§āύ
moved to heap: factor func literal escapes to heap
āϤāĻžāϰ āĻŽāĻžāύā§:
factorheap āĻ āĻāϞ⧠āĻā§āĻā§āĨ¤closure function āĻ heap allocatedāĨ¤
⨠āĻā§āύ Closure āĻ Struct āϞāĻžāĻā§?
Closure āĻā§ context āĻŦāĻž environment (captured variables) āĻĻāϰāĻāĻžāϰ āĻšā§ āϝāĻž function call āĻāϰ āĻŦāĻžāĻāϰ⧠āĻ āϝā§āύ āϤāĻžāϰ āĻ āϏā§āĻĨāĻŋāϤāĻŦ āĻāĻŋāĻā§ āĻĨāĻžāĻā§āĨ¤
āĻāĻ āĻāύā§āϝ Go āĻāĻāĻāĻŋ struct āϤā§āϰāĻŋ āĻāϰ⧠āϝāĻžāϤ⧠āϏ⧠context āϧāϰ⧠āϰāĻžāĻāϤ⧠āĻĒāĻžāϰā§āĨ¤
đ Summary:
Anonymous function + captured variables āĻā§ āĻāĻāϏāĻžāĻĨā§ āϰāĻžāĻāĻžāϰ āĻāύā§āϝ hidden struct + heap allocation (if escapes) + GC managementāĨ¤
āĻāĻāĻž Go āĻāϰ simplicity āĻāϰ power āĻāϰ āĻāĻāĻāĻž āĻŦā§ āĻāĻžāϰāĻŖ āĻšāϞ⧠āĻāĻ ClosureāĨ¤
Morshedul islam Munna
- Software Engineer
Linkedin: https://www.linkedin.com/in/morshedulmunna/
Email: morshedulmunna1@gmail.com




