我正在跟進Golang 將通用 JSON 對象解碼為多種格式之一,作為解組通用 json 的一種方式。我將有許多不同的類型,其他人可以添加這些類型,因此硬編碼 case 語句是不可行的。我也不想將類型硬編碼為字符串,但讓使用庫的人選擇“查找”名稱,以防他們以后想重命名其底層結構。我基本上是在尋找這樣的東西:type myInterface interface { Something() // irrelevant, just to show you It's not about interface{}}type myBar struct {} // fulfils myInterfacetype mySomething struct {} // fulfils myInterfacevar types = make(map[string]type) // <--- Obvious Pseudo code ;)types["foo:bar"] = myBar // done by whoever uses the librarytypes["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}我有一種感覺,我把整個問題想得太多了?;蛘呶以噲D將 Go 轉變為與其基本哲學相沖突的東西。我非常開放并感謝任何建議對整個問題提出不同的方法
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
必須types
是 a map[string]myInterface
,并注冊一個類型,讓調用者將該類型的空值(不是引用)存儲到映射中。然后,要解組,您可以通過從映射中復制空值、解組到其中并返回它(或對它的引用)來“獲取類型”。接口值將完成識別所需類型的工作。另外,如果用戶希望將某些字段默認為非零/空值,以防它們未在 JSON 中提供,他們實際上可以通過將這些值存儲在類型映射的結構中來實現。
- 1 回答
- 0 關注
- 149 瀏覽
添加回答
舉報
0/150
提交
取消