← ClaudeAtlas

go-functional-optionslisted

The functional options pattern for Go constructors and public APIs. Use when designing APIs with optional configuration, especially with 3+ parameters.
dwana1/golang-skills · ★ 0 · DevOps & Infrastructure · score 72
Install: claude install-skill dwana1/golang-skills
# Functional Options Pattern > **Source**: Uber Go Style Guide Functional options is a pattern where you declare an opaque `Option` type that records information in an internal struct. The constructor accepts a variadic number of these options and applies them to configure the result. ## When to Use Use functional options when: - **3+ optional arguments** on constructors or public APIs - **Extensible APIs** that may gain new options over time - **Clean caller experience** is important (no need to pass defaults) ## The Pattern ### Core Components 1. **Unexported `options` struct** - holds all configuration 2. **Exported `Option` interface** - with unexported `apply` method 3. **Option types** - implement the interface 4. **`With*` constructors** - create options ### Option Interface ```go type Option interface { apply(*options) } ``` The unexported `apply` method ensures only options from this package can be used. ## Complete Implementation > **Source**: Uber Go Style Guide ```go package db import "go.uber.org/zap" // options holds all configuration for opening a connection. type options struct { cache bool logger *zap.Logger } // Option configures how we open the connection. type Option interface { apply(*options) } // cacheOption implements Option for cache setting (simple type alias). type cacheOption bool func (c cacheOption) apply(opts *options) { opts.cache = bool(c) } // WithCache enables or disables caching. func WithCache(c boo