rmoff's random ramblings
about talks

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

Published Jun 29, 2020 by in Go, Golang, Function Closures at https://rmoff.net/2020/06/29/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.

Note
Learning Go : Background

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

  • https://www.calhoun.io/5-useful-ways-to-use-closures-in-go/

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 

📺 More Episodes… 🔗

  • Kafka and Go

    • S02E00 - Kafka and Go

    • S02E01 - My First Kafka Go Producer

    • S02E02 - Adding error handling to the Producer

    • S02E03 - Kafka Go Consumer (Channel-based)

    • S02E04 - Kafka Go Consumer (Function-based)

    • S02E05 - Kafka Go AdminClient

    • S02E06 - Putting the Producer in a function and handling errors in a Go routine

    • S02E07 - Splitting Go code into separate source files and building a binary executable

    • S02E08 - Checking Kafka advertised.listeners with Go

    • S02E09 - Processing chunked responses before EOF is reached

  • Learning Go

    • S01E00 - Background

    • S01E01 - Pointers

    • S01E02 - Slices

    • S01E03 - Maps

    • S01E04 - Function Closures

    • S01E05 - Interfaces

    • S01E06 - Errors

    • S01E07 - Readers

    • S01E08 - Images

    • S01E09 - Concurrency (Channels, Goroutines)

    • S01E10 - Concurrency (Web Crawler)


Robin Moffatt

Robin Moffatt works on the DevRel team at Confluent. He likes writing about himself in the third person, eating good breakfasts, and drinking good beer.

Story logo

© 2025