Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior between calling function directly and using pointer

Tags:

go

I am new to Go language and got confused with the following code

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    previous := 0
    current := 1
    return func () int{
        current = current+previous
        previous = current-previous
        return current

    }
}

func main() {
    f := fibonacci
    for i := 0; i < 10; i++ {
        fmt.Println(f()())
    }
}

This code is supposed to print out the Fibonacci Sequence (first 10), but only print out 10 times 1. but if I change the code to:

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

Then it is working fine. The output is the Fibonacci sequence.

Could any one help me explain this?

Thanks

like image 574
Luke Avatar asked Nov 23 '25 05:11

Luke


1 Answers

fibonacci() creates a new fibonacci generator function. fibonacci()() does the same, and then calls it once, returns the result and discards the generator, never to be used again. If you call that in a loop, it'll just keep creating new generators and only using their first value.

If you want more than just the first value, you need to do exactly what you did in your second example. Store the generator itself in a variable and then call the same generator multiple times.

like image 161
Matti Virkkunen Avatar answered Nov 25 '25 20:11

Matti Virkkunen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!