当前位置: > > > > 如何将 golang 结构编码为 TOML 并使用 BurntSushi/toml 库写入文件?
来源:stackoverflow
2024-04-20 18:42:27
0浏览
收藏
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何将 golang 结构编码为 TOML 并使用 BurntSushi/toml 库写入文件?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
使用 burntsushi/toml 库读取和解码 toml 文件非常简单:
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
我想做相反的事情:获取一个结构,将其编码为 toml 并将其写入文件。
解决方案
没有单个函数可以编码和写入文件,因此您需要:
- 使用
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) }
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持!更多关于Golang的相关知识,也可关注公众号。