Go中的猴子修补实例

I have structure with some fields inside and I Marshall that structure and return json to client. I cannot change json nor structure but in some corner cases I have to add one more additional flag. Is possible instance monkey patching in Go and how to achieve that ? I can solve this through inheritance but I would love to see if dynamically adding property to instance of structure is possible in Go.

No, you can't monkeypatch things like that in Go. Structs are defined at compile time, you can't add fields at runtime.

I can solve this through inheritance (…)

No you can't because there is no inheritance in Go. You can solve it through composition:

type FooWithFlag struct {
    Foo
    Flag bool
}

you could also use the json:",omitempty" option on your flag

an example:

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

You can always define a custom Marshaler / Unmarshaler interface and handle it in your type:

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
}

playground