Thursday, June 19, 2025
HomeGolang"Objects are a poor man's closure" instance - Technical Dialogue

“Objects are a poor man’s closure” instance – Technical Dialogue


Right here you’ve two closures with shared state. Not sure whether or not that qualifies…

Why wouldn’t it? createCounter may return one closure to increment c, however this instance exhibits how one can group closures collectively to create an object with shared state.

Yea, however now you’ve a “group”.

Maybe you had been fascinated by one thing like (Go Playground):

func NewCounter() func(int) int {
	var coutnter int

	return func(x int) int {
		coutnter += x

		return coutnter
	}
}

func most important() {
	c := NewCounter()

	fmt.Println("+1:", c(1))
	fmt.Println("+2:", c(2))
	fmt.Println("-1:", c(-1))
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments