Loading

链式函数

// 假设n1,n2是必填项,o1,o2是选择项
type Conf struct {
N1 string
N2 int
O1 string
O2 int
}

// 链式函数
type Option func(conf Conf) (Conf, error)

func O1(o1 string) Option {
return func(conf Conf) (Conf, error) {
if o1 == "" {
return nil, errors.New("xxx")
}

	conf.O1 = o1
	return conf, nil
}

}

func O2(o2 int) Option {
return func(conf Conf) (Conf, error) {
if o2 == 0 {
return nil, errors.New("yyy")
}

	conf.O2 = o2
	return conf, nil
}

}

// 可传入Option组,
func NewConf(n1 string, n2 int, opts ...Option) (*Conf, error) {
conf := Conf{
N1: n1,
N2: n2,
O1: "default",
O2: 100,
}

for _, opt := range opts {
	c, err := opt(&conf)
              // return ...
}

  // return ...

}

// 使用
conf, err := NewConf("emm", 10, O1("one"), O2(20))

posted @ 2021-01-24 19:21  ly_arise  阅读(164)  评论(0编辑  收藏  举报