我想從 toml 文件中讀取配置。會議/會議.tomldb_host = "127.0.0.1"db_port = 3306db_user = "root"db_password ="123456"conf/conf.go 文件package confimport ( "log" "github.com/BurntSushi/toml")type appcfg struct { DbHost string `toml:"db_host"` DbPort string `toml:"db_port"` DbUser string `toml:"db_user"` DbPassword string `toml:"db_password"`}var ( App *appcfg defConfig = "./conf/conf.toml")func init() { var err error App, err = initCfg() log.Println(App.DbHost)}func initCfg() (*appcfg, error) { app := &appcfg{} _, err := toml.DecodeFile(defConfig, &app) if err != nil { return nil, err } return app, nil}當我運行這個程序時,我收到一個我不知道如何修復的錯誤:恐慌:運行時錯誤:無效的內存地址或零指針取消引用
1 回答
MYYA
TA貢獻1868條經驗 獲得超4個贊
(重新發布 Comin2021現在已刪除的英文答案,因為它已被 OP 接受)
您定義了DbPortas的類型,string但它在您的配置文件中顯示為整數。更改如下:
type appcfg struct {
DbHost string `toml:"db_host"`
DbPort int64 `toml:"db_port"` // change this
DbUser string `toml:"db_user"`
DbPassword string `toml:"db_password"`
}
還要檢查initCfg第二個返回值err是否為空并記錄它。
- 1 回答
- 0 關注
- 192 瀏覽
添加回答
舉報
0/150
提交
取消
