为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 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 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信