首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将golang编码为TOML并使用BurntSushi/toml库写入文件?

如何将golang编码为TOML并使用BurntSushi/toml库写入文件?
EN

Stack Overflow用户
提问于 2019-12-12 20:03:50
回答 1查看 2.3K关注 0票数 0

使用BurntSushi/toml库读取和解码TOML文件非常简单:

代码语言:javascript
复制
var config Config // struct that matches the structure of the TOML file
if _, 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

我想做相反的事情:取一个struct,将其编码为TOML并将其写入文件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-12 20:03:50

没有要对文件进行编码和写入的单一函数,因此您需要:

使用os.Create()

  • Encode创建一个文件--使用toml.Encoder.Encode()

将结构转换为文件

让我们假设我们有一个要以TOML格式写入文件的结构config

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59311942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档