Go中的猴子补丁实例

Go中的猴子补丁实例,go,monkeypatching,Go,Monkeypatching,我有一个包含一些字段的结构,我整理该结构并将json返回给客户机。我无法更改json或结构,但在某些情况下,我必须再添加一个标志。Go中是否可能实例猴子补丁,以及如何实现? 我可以通过继承来解决这个问题,但我想看看在Go中是否可以动态地向结构实例添加属性 不,你不能在围棋中胡闹。结构是在编译时定义的,不能在运行时添加字段 我可以通过继承来解决这个问题(…) 不,你不能,因为围棋没有继承权。您可以通过组合来解决此问题: 不,你不能在围棋里胡闹。结构是在编译时定义的,不能在运行时添加字段 我可以通过

我有一个包含一些字段的结构,我整理该结构并将
json返回给客户机
。我
无法更改json或结构,但在某些情况下,我必须再添加一个标志。Go中是否可能
实例猴子补丁
,以及如何实现?
我可以通过继承来解决这个问题,但我想看看在Go中是否可以动态地向结构实例添加属性

不,你不能在围棋中胡闹。结构是在编译时定义的,不能在运行时添加字段

我可以通过继承来解决这个问题(…)

不,你不能,因为围棋没有继承权。您可以通过组合来解决此问题:


不,你不能在围棋里胡闹。结构是在编译时定义的,不能在运行时添加字段

我可以通过继承来解决这个问题(…)

不,你不能,因为围棋没有继承权。您可以通过组合来解决此问题:


您还可以在您的标志上使用
json:,ommitempty“
选项

例如:


您还可以在您的标志上使用
json:,ommitempty“
选项

例如:


您始终可以定义自定义/接口并在您的类型中处理它:

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
}

您始终可以定义自定义/接口并在您的类型中处理它:

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
}