Apply functional options and adapters
Apply functional options and adapters
Functional options are functions that customize a configuration during construction. They help when a component has many optional settings but stable defaults. Apply options in a documented order, then validate the final configuration before exposing the component. An adapter translates an existing interface or function into the contract a consumer expects.
package main
import ( "errors" "fmt")
type Config struct{ Limit int }type Option func(*Config)
func WithLimit(n int) Option { return func(c *Config) { c.Limit = n } }func New(opts ...Option) (Config, error) { c := Config{Limit: 10} for _, o := range opts { if o == nil { return Config{}, errors.New("nil option") } o(&c) } if c.Limit < 1 { return Config{}, errors.New("invalid limit") } return c, nil}func main() { a, e := New() fmt.Println(a.Limit, e) b, e := New(WithLimit(2), WithLimit(4)) fmt.Println(b.Limit, e) _, e = New(WithLimit(0)) fmt.Println(e)}Options are applied left to right, so the last limit wins. The constructor checks the resulting value. This educational configuration contains only an integer; mutable slices or maps require copying or an ownership contract. Prefer a simple config struct when options add complexity without benefit. Avoid options that perform external side effects or retain the mutable configuration pointer.
Expected output:
10 <nil>4 <nil>invalid limitAdapt a function to an interface
package main
import ( "fmt")
type Lookup interface{ Find(string) (string, bool) }type LookupFunc func(string) (string, bool)
func (f LookupFunc) Find(k string) (string, bool) { return f(k) }func show(l Lookup, k string) { v, ok := l.Find(k); fmt.Println(v, ok) }func main() { m := map[string]string{"a": "tea"} show(LookupFunc(func(k string) (string, bool) { v, ok := m[k]; return v, ok }), "a")}The named function type implements Find and delegates to the original function. The adapter does not invent a successful result if the key is absent. A nil function is not a usable implementation. For a shared map, concurrency and ownership must be handled separately.
Expected output:
tea trueTry it locally
Create a configuration with default label tea and a WithLabel option; reject empty final labels. Print the default, a custom label coffee, and the error for an empty label.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Professional architecture 02: Apply functional options and adapters
Check the lesson objective before moving on.
When should final validation occur in this constructor?
What makes LookupFunc satisfy Lookup?