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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM