我嘗試做什么我為 s 編寫了一個模板App每個App都有一個配置 - 因此我想將 s 存儲Config到App struct.我所有的configs 都存儲在其中JSON- 因此我想提供一個通用func的加載JSONconst JSON = `{ "Name": "TestConfig"}`注意:我嘗試使用和不使用指針來解決我的問題,兩者都會導致相同的錯誤消息 - 兩個版本都包含在下面。因此,讓我們將 App-Template 視為:type App struct { config interface{} configPtr *interface{} }和一個Configuration:// ConfigurationA is an actual implementation of the Config (Application A)type ConfigurationA struct { Name string // ... add more properties here}此外,我實現了一個func加載Configfromfile并將其存儲在Appfunc (a *App) GeneralConfigLoader(jsonData string, v interface{}) (err error) { // load json -> struct err = json.Unmarshal([]byte(jsonData), &v) if err != nil { fmt.Println("error unmarshalling JSON data") return err } a.config = v a.configPtr = &v return nil}由于我有一個具有一般負載的應用程序,func因此現在應該可以創建一個簡單func的將空接口轉換為正確的配置結構。// Config - Config of the Appfunc Config(a *App) *ConfigurationA { var cfg ConfigurationA = a.config.(ConfigurationA) return &cfg}// ConfigPtr - Config of the Appfunc ConfigPtr(a *App) *ConfigurationA { var i interface{} = *a.configPtr return i.(*ConfigurationA)}如果我將其總結為可執行文件,例如:func main() { var conf ConfigurationA // the interface used as Configuration var a = &App{} a.GeneralConfigLoader(JSON, conf) //panics: interface conversion: interface {} is map[string]interface {}, not main.ConfigurationA var cfg = Config(a) fmt.Println("cfg -> ", cfg) //panics: interface conversion: interface {} is map[string]interface {}, not *main.ConfigurationA var cfgPtr = ConfigPtr(a) fmt.Println("cfgPtr -> ", cfgPtr)}應用程序恐慌(上一節中的評論......)為什么 go 會省略類型信息?或者更好...為什么我不能將配置轉換回原來的樣子,因為我知道它是什么...?注意如果我不使用這個通用加載器并創建它確實有效的具體實現!問題:我究竟做錯了什么?使用 go 是不可能的(懷疑)?
1 回答

回首憶惘然
TA貢獻1847條經驗 獲得超11個贊
將指針傳遞給 GeneralConfigLoader。解組該指針。刪除字段App.configPtr。它沒有用,也不符合您的期望。
func (a *App) GeneralConfigLoader(jsonData string, v interface{}) (err error) {
err = json.Unmarshal([]byte(jsonData), v) // & removed here
if err != nil {
fmt.Println("error unmarshalling JSON data")
return err
}
a.config = v
return nil
}
func Config(a *App) *ConfigurationA {
return a.config.(*ConfigurationA)
}
像這樣加載配置:
var config ConfigurationA
var a = &App{}
a.GeneralConfigLoader(JSON, &config) // & added here
- 1 回答
- 0 關注
- 89 瀏覽
添加回答
舉報
0/150
提交
取消