1

Functional options in Go

 3 years ago
source link: https://thewebivore.com/functional-options-in-go/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Functional options in Go
Internet-ivore, development-ivore, design-ivore, event-ivore, fun-ivore. Technology, fun, and Philadelphia.

Skip to content

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”.

Posted in: Blog

Tags:go golang

Leave a Reply Cancel reply

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

Comment

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

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

Post navigation


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK