DEV Community

Raihanul Islam Sharif
Raihanul Islam Sharif

Posted on

Closure Bangla


🚀 Go Language āĻ Closure + Escape Analysis
āĻĒā§āϰ⧋āĻ—ā§āϰāĻžāĻŽāĻŋāĻ‚-āĻ closure āĻāĻ•āϟāĻž āĻĻāĻžāϰ⧁āĻŖ āĻ•āύāϏ⧇āĻĒā§āϟāĨ¤
Closure āĻŽāĻžāύ⧇ āĻšāϞ⧋ → āĻāĻ•āϟāĻž function, āϝ⧇āϟāĻž outer function āĻāϰ āϭ⧇āϤāϰ⧇āϰ variable āϕ⧇ "āĻŽāύ⧇ āϰāĻžāϖ⧇", āĻāĻŽāύāĻ•āĻŋ outer function āĻļ⧇āώ āĻšāϝāĻŧ⧇ āϗ⧇āϞ⧇āĻ“āĨ¤
👉 Example in Go:
func counter() func() int {
x := 0
return func() int {
x++
return x
}
}
āĻāĻ–āĻžāύ⧇ counter() āĻĢāĻžāĻ‚āĻļāύ return āĻ•āϰāϛ⧇ āĻāĻ•āϟāĻž inner functionāĨ¤
Inner function āĻāĻ–āύāĻ“ x āĻ­ā§āϝāĻžāϰāĻŋāϝāĻŧ⧇āĻŦāϞ āĻŽāύ⧇ āϰāĻžāĻ–āϛ⧇āĨ¤
āϤāĻžāĻšāϞ⧇ āĻĒā§āϰāĻļā§āύ āφāϏāϞ⧋ → outer function āϤ⧋ āĻļ⧇āώ āĻšāϝāĻŧ⧇ āϗ⧇āϛ⧇,x āĻŦ⧇āρāĻšā§‡ āϰāχāϞ⧋ āĻ•āĻŋāĻ­āĻžāĻŦ⧇? 🤔
āĻāĻ–āĻžāύ⧇āχ āφāϏ⧇ Escape AnalysisāĨ¤

Go compiler āĻāĻ•āϟāĻž process āϚāĻžāϞāĻžāϝāĻŧ āϝ⧇āϟāĻžāϕ⧇ āĻŦāϞ⧇ escape analysisāĨ¤
āĻāϟāĻž basically āĻšā§‡āĻ• āĻ•āϰ⧇ → āϕ⧋āύ āĻ­ā§āϝāĻžāϰāĻŋāϝāĻŧ⧇āĻŦāϞ stack āĻ āĻĨāĻžāĻ•āĻŦ⧇ āφāϰ āϕ⧋āύāϟāĻž heap āĻ escape āĻ•āϰāĻŦ⧇āĨ¤
🔎 āωāĻĒāϰ⧇āϰ āϕ⧋āĻĄ x → heap āĻ āϚāϞ⧇ āϗ⧇āϛ⧇āĨ¤
āĻ•āĻžāϰāĻŖ closure āĻĢāĻžāĻ‚āĻļāύ return āĻšāĻšā§āϛ⧇, āφāϰ āϤāĻžāϰ āĻŦāĻžāχāϰ⧇ āĻĨ⧇āϕ⧇āĻ“ x āĻāϰ āĻĻāϰāĻ•āĻžāϰ āĻšāĻšā§āϛ⧇āĨ¤
📌 Bottom line:

Local variable āĻšāϞ⧇ → normally stack āĻ āĻĨāĻžāϕ⧇
Closure āĻŦāĻž long-living object āĻšāϞ⧇ → escape āĻ•āϰ⧇ heap āĻ āϝāĻžāϝāĻŧ💡 āφāĻŽāĻžāϰ āĻŽāϤ⧇ āĻļ⧁āϰ⧁āϤ⧇ closure āĻŦ⧁āĻāĻž āϜāϰ⧁āϰāĻŋ, āĻ•āĻžāϰāĻŖ āĻāϟāĻž āĻšāϞ⧋ conceptāĨ¤ āϤāĻžāϰāĻĒāϰ naturally curiosity āφāϏāĻŦ⧇ — “variable āĻŦāĻžāρāϚāϞ⧋ āĻ•āĻŋāĻ­āĻžāĻŦ⧇?” → āϤāĻ–āύ escape analysis āĻŦā§‹āĻāĻž easy āĻšāϝāĻŧ⧇ āϝāĻžāĻŦ⧇āĨ¤
👉 āφāĻĒāύāĻžāϰ āĻŽāϤ⧇ Go āĻļ⧇āĻ–āĻžāϰ āĻļ⧁āϰ⧁āϤ⧇ closure & escape analysis – āϕ⧋āύāϟāĻž āφāϗ⧇ āĻŦā§‹āĻāĻž āωāϚāĻŋāϤ?

Top comments (0)