Go Default Value Setting ========================== ###### tags: `Go` ```go package main import "time" const ( CommonCart = "common" BuyNowCart = "buyNow" ) // 把 Optional properties統一到一個結構中, 並且把該類給私有化 type cartExts struct { CartType string TTL time.Duration } // 定義一個interface, 提供一個apply方法 // 方法的參數是Optional properties類別的指針類型, 因為要直接對該物件進行修改 type CartExt interface { apply(*cartExts) } // 利用該interface的實現, 封裝optional 屬性修改的方法, 建議已With+屬性名 func WithCartType(cartType string) CartExt { return newFuncCartExt(func(exts *cartExts) { exts.CartType = cartType }) } func WithTTL(d time.Duration) CartExt { return newFuncCartExt(func(exts *cartExts) { exts.TTL = d }) } // 這裡新增了類型,標記這個函數 // 定義一個Func type, 這func的參數要跟apply interface保持一致 type tempFunc func(*cartExts) // 實現 CartExt interface type funcCartExt struct { f tempFunc } // 具體的interface實現 func (fdo *funcCartExt) apply(e *cartExts) { fdo.f(e) } func newFuncCartExt(f tempFunc) *funcCartExt { return &funcCartExt{f: f} } type DemoCart struct { UserID string ItemID string Sku int64 Ext cartExts } var DefaultExt = cartExts{ CartType: CommonCart, // 默認是普通購物車 TTL: time.Minute * 60, // 默認60MIN過期 } func NewCart(userID string, Sku int64, exts ...CartExt) *DemoCart { c := &DemoCart{ UserID: userID, Sku: Sku, Ext: DefaultExt, // 設定默認值 } for _, ext := range exts { ext.apply(&c.Ext) } return c } func main() { exts := []CartExt{ WithCartType(CommonCart), WithTTL(1000), } NewCart("Eddie", 888, exts...) } ```