package main
import "fmt"
type options struct {
cache bool
logger string
}
type Option interface {
apply(*options)
}
type cacheOption bool
func (c cacheOption) apply(opts *options) {
opts.cache = bool(c)
}
func WithCache(c bool) Option {
return cacheOption(c)
}
type loggerOption struct {
Log string
}
func (l loggerOption) apply(opts *options) {
opts.logger = l.Log
}
func WithLogger(log string) Option {
return loggerOption{Log: log}
}
// Open creates a connection.
func Open(
addr string,
opts ...Option,
){
options := options{
cache: true,
logger: "hello",
}
fmt.Println(">>addr: ",addr)
fmt.Println(">>opts: ",opts)
for _, o := range opts {
o.apply(&options)
}
}
func main(){
var option Option
option = new(cacheOption)
option.apply(&options{cache:true})
var option1 Option
option1 = new(loggerOption)
option1.apply(&options{logger:"hi,"})
Open("localhost",[]Option{option,option1}...)
}