package main
import (
"fmt"
)
type Config struct {
path string
isUseFile bool
}
type ConfigOption func(config *Config) error
func WithPath(path string) ConfigOption {
return func(config *Config) error {
if path == "" {
return fmt.Errorf("path is empty")
}
config.path = path
return nil
}
}
func WithUseFile(isUseFile bool) ConfigOption {
return func(config *Config) error {
config.isUseFile = isUseFile
return nil
}
}
func NewConfig(opts ...ConfigOption) (*Config, error) {
var config *Config = &Config{}
for _, opt := range opts {
if err := opt(config); err != nil {
return config, err
}
}
return config, nil
}
func main() {
config, err := NewConfig(WithPath("123"), WithUseFile(false))
fmt.Printf("path:%s isUseFile:%v err:%v\n", config.path, config.isUseFile, err)
}
![]()