Go 参数配置默认值设计架构

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
    }
}

你可能感兴趣的:(Go 参数配置默认值设计架构)