亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 golang 結構編碼為 TOML 并使用 BurntSushi/toml 庫寫入文件?

如何將 golang 結構編碼為 TOML 并使用 BurntSushi/toml 庫寫入文件?

Go
德瑪西亞99 2023-08-14 14:54:39
使用 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個贊

沒有單個函數可以編碼和寫入文件,因此您需要:

  1. 使用創建文件os.Create()

  2. 使用以下命令將結構編碼到文件中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)


}


查看完整回答
反對 回復 2023-08-14
  • 1 回答
  • 0 關注
  • 230 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號