我的结构中包含一些字段,我对该结构进行Marshall并返回json to client
。我cannot change json nor structure
但在某些角落的情况下,我还要添加一个额外的标志。 Go中可能instance monkey patching
以及如何实现这一目标?
我可以通过继承解决这个问题,但我很想看看是否可以在Go中动态地向结构实例添加属性。
答案 0 :(得分:4)
不,你不能在Go中做类似的事情。结构是在编译时定义的,您不能在运行时添加字段。
我可以通过继承(...)
来解决这个问题
不,你不能,因为Go中没有继承。您可以通过组合:
来解决它type FooWithFlag struct {
Foo
Flag bool
}
答案 1 :(得分:1)
您始终可以定义自定义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
}
答案 2 :(得分:0)