state aware functions

tags: learning go programming

content

  • in Python OOP, it’s easy to have class and remember its state:
class Adder:
	def __init__(self, num):
		self.num = num
	def add(self, num):
		self.num += num
		return self.num
  • we have a class that is a persistent object, which has its own state
addObj = Adder(5)
addObj.add(5)  # 10
addObj.add(5)  # 15
  • how to achieve the same thing in Go without class?
type Adder func(int) int
func newAdder(num int) Adder {
	sum := num
	return func(x int) int {
		sum += x
		return sum
	}
}
 
adder := newAdder(5)
adder(5)  // 10
adder(5)  // 15

up

down

reference