π 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:
-
https://gobyexample.com/closures
I like this site as it links all its examples to The Go Playground where you can try out each code block
-
http://tleyden.github.io/blog/2016/12/20/understanding-function-closures-in-go/
This comment was particularly useful
Essentially you can think of them like stateful functions , in the sense that they encapsulate state.
It made things click a bit for me, more than the abstract alphabet soup that other examples used :)
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
}
}
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
Top comments (0)