Skip to content

Functional options in Go

A while back, someone made a PR related to some code I’d written to make a bit of functionality optional, rather than required behavior (in this case, having a set of default .terraformignore rules if you don’t have a .terraformignore file). Since the library is used in multiple places, this made sense.

The implementation of this used a pattern that was new to me: “functional options”. I asked Rusty (the author of the PR) later about the changeset, because it “looked like a pattern” and it is a named pattern!

Functional options for friendly APIs

The two things I thought were interesting about this interaction was, first, learning about this pattern so I can implement it elsewhere when it makes sense. For example, I can see that the original function signature of Pack has something that looks like an option already (dereference), and that could be why it made sense, if making something else optional, to go ahead and implement this pattern.

The second thing is recognizing something as a pattern. Two clues were using a combination of words new to me (“is a functional option“) and that it looked like a useful shape that might bear repeating (aka, a pattern).

This post now also serves as a useful historical link (for me, ha) to a diff for “how to refactor into functional options”.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.