亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

Go 中的 Monkey 補丁實例

Go 中的 Monkey 補丁實例

Go
繁星點點滴滴 2021-10-18 16:37:11
我的結構里面有一些字段,我把這個結構編組并返回json to client。我cannot change json nor structure但在某些極端情況下,我必須再添加一個額外的標志。instance monkey patching在 Go 中是否可行以及如何實現?我可以通過繼承來解決這個問題,但我很想看看在 Go 中是否可以動態地向結構實例添加屬性。
查看完整描述

3 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

不,你不能在 Go 中對這樣的東西進行猴子補丁。結構在編譯時定義,您不能在運行時添加字段。


我可以通過繼承來解決這個問題(...)


不,你不能,因為 Go 中沒有繼承。您可以通過組合解決它:


type FooWithFlag struct {

    Foo

    Flag bool

}


查看完整回答
反對 回復 2021-10-18
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

你總是可以定義一個自定義Marshaler/Unmarshaler接口并在你的類型中處理它:


type X struct {

    b bool

}


func (x *X) MarshalJSON() ([]byte, error) {

    out := map[string]interface{}{

        "b": x.b,

    }

    if x.b {

        out["other-custom-field"] = "42"

    }

    return json.Marshal(out)

}


func (x *X) UnmarshalJSON(b []byte) (err error) {

    var m map[string]interface{}

    if err = json.Unmarshal(b, &m); err != nil {

        return

    }

    x.b, _ = m["b"].(bool)

    if x.b {

        if v, ok := m["other-custom-field"].(string); ok {

            log.Printf("got a super secret value: %s", v)

        }

    }

    return

}


查看完整回答
反對 回復 2021-10-18
  • 3 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號