Go 参数配置默认值设计架构
2020-04-02 本文已影响0人
swifterlc
package server
//定义选项结构
type Options struct {
UserName string
Password string
Host string
Port int16
}
type Option func(*Options)
type Server struct {
Options Options
//other
}
func NewServer(options ...Option) *Server{
s:= &Server{Options:Options{
UserName: "root",
Password: "1234",
Host: "localhost",
Port: 8000,
}}
for _,v := range options{
v(&s.Options)
}
//other
return s
}
func UserName(name string) Option{
return func(o *Options) {
o.UserName = name
}
}