Why value to variable increases here

Hey Reader’s,

I am unable to understand to why value of x increase even after scope end for varaiable ‘x’ in function foo(). It’s must reset to zero everytime I called a function. This this not happening why?

Here Is The Code

Thank You

1 Like

That’s called a closure. Basically, when doing a := foo() what happens is that var x int is declared and initialized to 0 and a is assigned the returned function from foo(), i.e.:

func() int {
	return x

So calling a() later only executes the increment and returns the value, it doesn’t initialize x again. The interesting thing is that this anonymous function that’s assigned to a closes over x, that is it may refer to and keep track of x even though it’s not referenced anywhere else.

Here’s a brief but better explained article: https://www.calhoun.io/what-is-a-closure/


Great explanation! Closures are something I need to read up on more.

Thanks for sharing your code @M_A_D_H_U_R I’m going to play around with this after I read a bit more on the subject.

1 Like