// 服務結構體 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))