package main
import "fmt"
func fib_seq() func() int {
n0, n1 := 0, 1
return func() int {
result := n0
n0, n1 = n1, n0 + n1
return result
}
}
func main() {
f := fib_seq()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
This is my Fibonacci sequence generator. The definition of result is unwanted (but necessary).
I wonder is there a way to execute x, y = y, x + y after return?
You may want to take a look at defer:
func fib_seq() func() int {
n0, n1 := 0, 1
return func() int {
defer func() {
n0, n1 = n1, n0 + n1
}()
return n0
}
}
Named return. But what you have is already readable enough.
func fib_seq() func() int {
n0, n1 := 0, 1
return func() (r int) {
r, n0, n1 = n0, n1, n0 + n1
return
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With