golang 服务或结构体可选参数的赋值

// 服务结构体
type Server struct {
    opts options //可选参数变量
    addr string
}

//可选参数列表
type options struct {
    A int
    B string
    C bool
    D int
}

// 为可选参数赋值的函数
type ServerOption func(*options)

func Afunc(a int) ServerOption {
    return func(o *options) {
        o.A = a
    }
}
func Bfunc(b string) ServerOption {
    return func(o *options) {
        o.B = b
    }
}
func Cfunc(c bool) ServerOption {
    return func(o *options) {
        o.C = c
    }
}

//新建服务
func NewServer(addr string, opt ....ServerOption) *Server {
    var opts options
    for _, o := opt {
        o(&options)
    }
    
    return &Server{
        opts: opts,
        addr: addr,
    }
}
// 实例说明
server := NewServer("aaaa", Afunc(1), Cfunc(true))

猜你喜欢

转载自www.cnblogs.com/share-ideas/p/11564310.html
今日推荐