使用 BurntSushi/toml 庫讀取和解碼 TOML 文件非常簡單:var config Config // struct that matches the structure of the TOML fileif _, err := toml.DecodeFile("path/to/file.toml", &config); err != nil { // failed to read and decode the file fmt.Fatal(err)}// at this point config struct contains the values from the file我想做相反的事情:獲取一個結構,將其編碼為 TOML 并將其寫入文件。
1 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
沒有單個函數可以編碼和寫入文件,因此您需要:
使用創建文件
os.Create()
使用以下命令將結構編碼到文件中
toml.Encoder.Encode()
假設我們有一個結構體config
想要以 TOML 格式寫入文件:
f, err := os.Create("path/to/file.toml")
if err != nil {
// failed to create/open the file
log.Fatal(err)
}
if err := toml.NewEncoder(f).Encode(config); err != nil {
// failed to encode
log.Fatal(err)
}
if err := f.Close(); err != nil {
// failed to close the file
log.Fatal(err)
}
- 1 回答
- 0 關注
- 230 瀏覽
添加回答
舉報
0/150
提交
取消