Load Config

Go语言抽象能力弱是语言特性限制的。
如下用工厂模式实现两种配置加载的逻辑。
获取配置方式一:

func GetConfig[T any]() T {
    switch any(*new(T)).(type) {
    case Config1:
       return any(Config1{}).(T)
    case Config2:
       return any(Config2{}).(T)
    default:
       return any(Config0{}).(T)
    }
}

type Config0 struct{}

type Config1 struct {
    Pkg string
}

type Config2 struct{}

获取配置方式二:

type Cfg interface {
	Load()
}

func GetConfig[T any]() (T, error) {
	cfg, ok := any(new(T)).(Cfg)
	if !ok {
		return *new(T), errors.New(fmt.Sprintf("%T type is not implement Cfg interface", *new(T)))
	}
	cfg.Load()
	return *any(cfg).(*T), nil
}

type Config0 struct {
	Name string
}

func (c *Config0) Load() {
	c.Name = "name"
}

type Config1 struct {
	Pkg string
}

func (c *Config1) Load() {
	c.Pkg = "pkg"
}

type Config2 struct {
	Operator string
}

func (c *Config2) Load() {
	c.Operator = "+"
}

你可能感兴趣的:(#,抽象的Go,go)