1
我想解決一些代碼從JSON文件中拉入配置。 當我試圖打造,我得到這個錯誤Golang:類型[type]不是表達式; json配置解析
type ConfigVars is not an expression
下面是我想與之合作的配置和程序代碼。我目前發現的每個例子都與下面的代碼類似。任何關於我做錯了什麼的建議?
-- Config File
{"beaconUrl":"http://test.com/?id=1"}
-- Program Code
package main
import (
"encoding/json"
"fmt"
"os"
)
type ConfigVars struct {
BeaconUrl string
}
func main() {
configFile, err := os.Open("config.json")
defer configFile.Close()
if err != nil {
fmt.Println("Opening config file", err.Error())
}
jsonParser := json.NewDecoder(configFile)
if err = jsonParser.Decode(&ConfigVars); err != nil {
fmt.Println("Parsing config file", err.Error())
}
}
只是更詳細地說明了一下,在你的'jsonParser'對象'Decode'方法需要一個指針(內存地址)寫入輸出到的'ConfigVars'實例。 'ConfigVars'是一種類型,意味着只有通過變量定義創建實例時纔會分配一個內存地址。即'var cfg ConfigVars' – Sthe