第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

設(shè)置 Option 對象時不可變 setter 和傳統(tǒng) setter 的區(qū)別

設(shè)置 Option 對象時不可變 setter 和傳統(tǒng) setter 的區(qū)別

Go
湖上湖 2022-05-05 17:57:50
在研究了一段時間的開源項目之后,我經(jīng)常在一個類的設(shè)置選項中看到這種模式。(讓我們說“不可變方法”)// list of possible optionstype Options struct {    Sampler sampler    SpanKind int}// define an apply function. which will be called when really initialize an objecttype Option func(*Options)// for each option. Return an function to apply that specific optionfunc WithSpanKind(spanKind int) Option {    return func(o *Options) {        o.SpanKind = spanKind    }}// then. we we build a new object, we just need to receive a list of optionfunc NewObject(options ...Option) Object {     final := &Options{}     // then apply each option to options     for _, option := range options {         option(final)     }     // then build an object based on the final object}與上述方法相比,還有另一種使用簡單 getter/setter 的方法。func (o *Options) SetSpanKind(kind int) {   o.spanKind = kind}// then. we we build a new object by using directly the Options objectfunc NewObject(option Options) Object {}我的問題是:這些方法之間有什么區(qū)別,為什么在我讀過的許多開源代碼中總是首選第一種方法。
查看完整描述

1 回答

?
寶慕林4294392

TA貢獻2021條經(jīng)驗 獲得超8個贊

至少在 Golang 中,getter 的使用是一種反模式。這種期權(quán)模式是眾所周知的。Setter 和 getter 在 Golang 空間中并不常見。


此選項模式有一個不錯的好處,您可以將多個選項函數(shù)傳遞給您的構(gòu)建器或構(gòu)造函數(shù),然后遍歷所有傳遞的選項以修改此選項類型,就像在您的示例中一樣


// then. we build a new object, we just need to receive a list of option

func NewObject(options ...Option) Object {

     final := &Options{}

     // then apply each option to options

     for _, option := range options {

         option(final)

     }

     // then build an object based on the final object

}

構(gòu)造函數(shù)調(diào)用示例:


NewObject(optionA, optionB, optionC, optionD)

吸氣劑和二傳手


https://golang.org/doc/effective_go.html#Getters


你肯定讀過有效的圍棋指南 -> https://golang.org/doc/effective_go.html


查看完整回答
反對 回復(fù) 2022-05-05
  • 1 回答
  • 0 關(guān)注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號