This note isn’t suggesting a pattern to follow, it’s a thought exercise. Let’s look at using a closure where we’d idiomatically use a struct.
For this thought exercise, we will implement a Fibonacci Number sequence generator two ways, once with a struct and once with a closure. We’ll use the same approach in both to compare.
So here’s a simple and idiomatic implementation with a struct:
package main
import "fmt"
type Fibonacci struct {
x1, x2 int
}
func NewFibonacci() *Fibonacci {
return &Fibonacci{-1,1}
}
func (f *Fibonacci) Next() int {
f.x1, f.x2 = f.x2, f.x1 + f.x2
return f.x2
}
func main() {
f := NewFibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f.Next())
}
}
#go #golang #closures-functions