Useful Functional-Options Tricks for Better Libraries
summary
Functional options in Go become a practical library design recipe: use a custom functional options type, apply options to an internal, non‑exported config struct, validate once and return errors (bundle multiple failures with Go 1.20 multierror), guarantee option order insensitivity, and make the produced middleware effectively immutable. Avoid hot‑path use for performance reasons. Enforce compile‑time safety for CORS by splitting factories into OptionAnon/OptionCred and use an opaque interface plus internal/risky packages and type aliases to surface only safe options.
AI-written summary · about
chapters (18)
- 0:00Functional options pattern
- 2:50Why functional options improve design
- 4:14Problems with naive approaches
- 7:22Functional options for expressiveness
- 8:45When not to use functional options
- 9:47Factory functions fail safely
- 12:16Order insensitivity in options
- 13:17Handling repeated option calls
- 14:43Immutability in middleware
- 16:09Benefits of custom option types
- 18:16Avoiding mutable behavior
- 19:00Intermediate non-exported structs
- 20:24Options as opaque interfaces
- 21:27Reducing boilerplate with adapters
- 22:33Enforcing constraints to prevent misuse
- 24:18Splitting options by access
- 25:22Advanced options in separate packages
- 26:25Summary and recommendations








