1
我正在跟進Golang Decoding Generic JSON Objects to One of Many Formats作爲解組泛型json的一種方式。我將會有許多不同類型的tho可以被其他人添加,所以硬編碼的case語句是不可行的。使用類型查找映射反編組泛型json
我也不想將該類型硬編碼爲字符串,但讓那些使用庫的人選擇「查找」名稱,以防他們稍後重新命名其基礎結構。
我基本上是在尋找這樣的事情:
type myInterface interface {
Something() // irrelevant, just to show you It's not about interface{}
}
type myBar struct {} // fulfils myInterface
type mySomething struct {} // fulfils myInterface
var types = make(map[string]type) // <--- Obvious Pseudo code ;)
types["foo:bar"] = myBar // done by whoever uses the library
types["1230988"] = mySomething // ...
type storageWrapper struct {
Type string
Data json.RawMessage
}
func loadSomething(id string) myInterface {
buf := db.load(id) // pseudo code but you get the idea
sw := &storageWrapper{}
json.Unmarshal(buf, sw)
// now the interesting part
targetType := types[sw.Type]
thing := &targetType{}
json.Unmarshal(sw.Data, thing)
return thing
}
我有這種感覺,我的得太多整個問題。或者,我正試圖彎曲與其底層哲學衝突的事物。我非常開放並且非常感謝任何意見,建議採取不同的方法來解決整個問題
接受這個答案是因爲它完成了工作。不過,我現在改變了我的代碼,所以它不再依賴於類型映射 – paukul