簡體   English   中英

Go中的猴子修補實例

[英]Monkey patching instance in Go

我具有內部包含一些字段的結構,並且將其編組,然后將json to client cannot change json nor structure但在某些特殊情況下,我必須再添加一個附加標志。 Go中可能有instance monkey patching以及如何實現? 我可以通過繼承解決此問題,但是我很想看看在Go中是否可以向結構實例動態添加屬性。

不,您無法在Go中進行類似的修補。 結構是在編譯時定義的,您不能在運行時添加字段。

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

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

type FooWithFlag struct {
    Foo
    Flag bool
}

您始終可以定義自定義的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
}

操場

您還可以在標志上使用json:",omitempty"選項

一個例子:

http://play.golang.org/p/ebmZLR8DLj

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM