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