Last active
September 29, 2022 03:27
-
-
Save qmdx00/bb1a6733565b62aafb4dfe8ad7c5a352 to your computer and use it in GitHub Desktop.
golang option pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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