我正在跟進(jìn)Golang 將通用 JSON 對(duì)象解碼為多種格式之一,作為解組通用 json 的一種方式。我將有許多不同的類型,其他人可以添加這些類型,因此硬編碼 case 語句是不可行的。我也不想將類型硬編碼為字符串,但讓使用庫(kù)的人選擇“查找”名稱,以防他們以后想重命名其底層結(jié)構(gòu)。我基本上是在尋找這樣的東西: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}我有一種感覺,我把整個(gè)問題想得太多了?;蛘呶以噲D將 Go 轉(zhuǎn)變?yōu)榕c其基本哲學(xué)相沖突的東西。我非常開放并感謝任何建議對(duì)整個(gè)問題提出不同的方法
1 回答

MMTTMM
TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
必須types
是 a map[string]myInterface
,并注冊(cè)一個(gè)類型,讓調(diào)用者將該類型的空值(不是引用)存儲(chǔ)到映射中。然后,要解組,您可以通過從映射中復(fù)制空值、解組到其中并返回它(或?qū)λ囊茫﹣怼矮@取類型”。接口值將完成識(shí)別所需類型的工作。另外,如果用戶希望將某些字段默認(rèn)為非零/空值,以防它們未在 JSON 中提供,他們實(shí)際上可以通過將這些值存儲(chǔ)在類型映射的結(jié)構(gòu)中來實(shí)現(xiàn)。
- 1 回答
- 0 關(guān)注
- 157 瀏覽
添加回答
舉報(bào)
0/150
提交
取消