DEV Community

Robin Moffatt
Robin Moffatt

Posted on • Originally published at rmoff.net on

Learning Golang (some rough notes) - S01E04 - Function Closures

πŸ‘‰ A Tour of Go : Function Closures

So far the Tour has been πŸ€” and 🧐 and even 🀨 but function closures had me 🀯 …

Each of the words on the page made sense but strung together in a sentence didn’t really make any sense to me.

Google resources threw up some nice explanations:

This one gets into some more hands-on examples

It also acted as a spoiler for the function closure exercise since that was the first example it gives :)

func fibonacci() func() int {
    f1 := 1
    f2 := 0
    return func() int {
        f1,f2 = f2, (f1+f2)
        return f1
    }
}
Enter fullscreen mode Exit fullscreen mode

I tweaked the version that I’d seen so that the return values stated at zero

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)