go-functional-options
Skill9 starsChanged 4 months agoMITView on GitHub
Use when designing a Go constructor or factory with 3+ optional parameters, or an API expected to grow new options over time. Covers the canonical Option interface pattern with unexported apply method, With* constructors, default values, and the interface-vs-closure tradeoff. Apply proactively when reviewing a New* function that takes many settings, even if the user didn't ask about functional options. Does not cover general function design (see go-functions).
1 other project uses a version of this.
Adopted by
Most recently taken up by
- cxuu/golang-skillstheir own version, first seen Jun 20, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- cxuu/golang-skills★ 165same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository26 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- go-clean-architectureSkill
- go-code-reviewSkill
- go-code-styleSkill
- go-concurrencySkill
- go-contextSkill
- go-control-flowSkill
- go-databaseSkill
- go-data-structuresSkill
- go-declarationsSkill
- go-defensiveSkill
- go-documentationSkill
- go-error-handlingSkill
- go-functionsSkill
- go-genericsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interfacesSkill
- go-lintingSkill
- go-loggingSkill
- go-namingSkill
- go-observabilitySkill
- go-packagesSkill
- go-performanceSkill
- go-swaggerSkill
- go-testingSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 16
The
optionsstruct is unexported: Only the package owns its shape. - Very specific: line 17
The
Optioninterface has an unexportedapplymethod: No external package can forge an option. - Very specific: line 19
Required parameters stay positional;: only the optional ones go through ...Option.
- Distinctive: line 129
If a default needs computation (a temp dir, a process-wide ID), build it once during the constructor — not at package init.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Functional Options
The functional options pattern lets a constructor stay backward compatible while accepting an open-ended set of optional settings. Callers pass only what differs from the defaults; new options never break old call sites.
Core Rules
- Reach for functional options at 3+ optional parameters or whenever the API will grow.
- The
optionsstruct is unexported. Only the package owns its shape. - The
Optioninterface has an unexportedapplymethod. No external package can forge an option. - Defaults go inside the constructor, before options are applied.
- Required parameters stay positional; only the optional ones go through
...Option. - Prefer the interface form over closures — it composes better with testing, debugging, and
fmt.Stringer.
When to Use What
| Situation | Pattern |
| 0–2 optional params, stable API | Plain positional or named args |
| Config that callers usually pass whole | Config struct |
| 3+ optional params, growing API | Functional options |
| Mix of "must set together" + "rare overrides" | Config struct + small Option set |
Read references/options-vs-struct.md when choosing between options and a plain config struct, or designing a hybrid.
The Canonical Pattern
package db
import "go.uber.org/zap"
// options is the package's private bag of settings.
type options struct {
cache bool
logger *zap.Logger
}
// Option configures Open.
type Option interface {
apply(*options)
}
// --- cacheOption -----------------------------------------------------------
type cacheOption bool
func (c cacheOption) apply(o *options) { o.cache = bool(c) }
// WithCache enables or disables the in-memory cache.
func WithCache(enabled bool) Option { return cacheOption(enabled) }
// --- loggerOption ----------------------------------------------------------
type loggerOption struct{ log *zap.Logger }
func (l loggerOption) apply(o *options) { o.logger = l.log }
// WithLogger sets the logger used by the connection.
func WithLogger(log *zap.Logger) Option { return loggerOption{log: log} }
// --- constructor -----------------------------------------------------------
// Open dials addr using the given options.
func Open(addr string, opts ...Option) (*Connection, error) {
o := options{
cache: true,
logger: zap.NewNop(),
}
for _, opt := range opts {
opt.apply(&o)
}
// ... build the connection from o
return &Connection{}, nil
}Caller Experience
db.Open(addr)
db.Open(addr, db.WithLogger(log))
db.Open(addr, db.WithCache(false), db.WithLogger(log))Compare to the alternative where all defaults must be repeated:
db.Open(addr, db.DefaultCache, zap.NewNop()) // tediousWhy an Interface, Not a Closure?
// The closure variant — discouraged
type Option func(*options)The interface form wins on:
- Testability — option values can be compared in tests.
- Debuggability — option types can implement
fmt.Stringer. - Documentation —
godoclists each option type explicitly. - Extensibility — options can implement additional interfaces (e.g.,
Validate()).
Closures are shorter to write; they pay for that shortness in introspection.
Defaults
Set defaults before applying options. A constructor that ignores its defaults is a bug magnet:
o := options{
cache: true,
logger: zap.NewNop(),
}
for _, opt := range opts {
opt.apply(&o)
}If a default needs computation (a temp dir, a process-wide ID), build it once during the constructor — not at package init.
Quick Reference
// 1. Unexported settings bag
type options struct { ... }
// 2. Exported interface, unexported method
type Option interface { apply(*options) }
// 3. One option type per setting
type widgetOption Widget
func (w widgetOption) apply(o *options) { o.widget = Widget(w) }
func WithWidget(w Widget) Option { return widgetOption(w) }
// 4. Constructor: defaults, then apply
func New(required string, opts ...Option) (*Thing, error) {
o := options{ /* defaults */ }
for _, opt := range opts { opt.apply(&o) }
return build(required, o)
}Anti-Patterns
| Anti-pattern | Why it hurts | Do this instead |
Exporting the options struct | External code mutates internals | Keep it unexported |
Option with an exported Apply | Anyone can build an option | Unexported apply method |
| Applying options before defaults | Defaults overwrite caller intent | Defaults first, then apply |
func Option(*options) closures | Opaque in tests/logs | Interface form |
| 7+ positional required params | Caller error-prone | Promote them into a config or options |
Mixing required and optional through ...Option | Required is no longer required | Keep required positional |
Verification Checklist
optionsis unexportedOptioninterface has an unexportedapply(*options)method- Each setting has a
With*constructor returningOption - Constructor sets defaults first, then applies options
- Required parameters are not hidden behind
...Option - No exported
ApplyorOption func(*options)slipped in - Doc comments explain each
With*and its default
References
- references/options-vs-struct.md — when to prefer a config struct, and how to combine the two
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

