Skip to content

Instantly share code, notes, and snippets.

@qmdx00
Last active September 29, 2022 03:27
Show Gist options
  • Save qmdx00/bb1a6733565b62aafb4dfe8ad7c5a352 to your computer and use it in GitHub Desktop.
Save qmdx00/bb1a6733565b62aafb4dfe8ad7c5a352 to your computer and use it in GitHub Desktop.
golang option pattern
package main
import (
"fmt"
"time"
)
type Option func(opts *Options)
var defaultConfig = Options{
Expiry: time.Second,
MaxSize: 100,
Name: "Default",
}
type Options struct {
Expiry time.Duration
MaxSize int
Name string
}
func New(opts ...Option) Options {
options := defaultConfig
for _, opt := range opts {
opt(&options)
}
return options
}
func WithOptions(options Options) Option {
return func(opts *Options) {
*opts = options
}
}
func WithExpiry(expiry time.Duration) Option {
return func(opts *Options) {
opts.Expiry = expiry
}
}
func WithMaxSize(max int) Option {
return func(opts *Options) {
opts.MaxSize = max
}
}
func WithName(name string) Option {
return func(opts *Options) {
opts.Name = name
}
}
func main() {
opt1 := New(WithExpiry(time.Minute))
opt2 := New(WithOptions(opt1), WithMaxSize(10), WithName("hello"))
fmt.Println(opt1, opt2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment