3 回答

TA貢獻1874條經(jīng)驗 獲得超12個贊
不,你不能在 Go 中對這樣的東西進行猴子補丁。結(jié)構(gòu)在編譯時定義,您不能在運行時添加字段。
我可以通過繼承來解決這個問題(...)
不,你不能,因為 Go 中沒有繼承。您可以通過組合解決它:
type FooWithFlag struct {
Foo
Flag bool
}

TA貢獻1816條經(jīng)驗 獲得超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
}
- 3 回答
- 0 關(guān)注
- 168 瀏覽
添加回答
舉報