使用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我想做相反的事情:取一个struct,将其编码为TOML并将其写入文件。
发布于 2019-12-12 20:03:50
没有要对文件进行编码和写入的单一函数,因此您需要:
使用os.Create()
toml.Encoder.Encode()将结构转换为文件
让我们假设我们有一个要以TOML格式写入文件的结构config:
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)
}https://stackoverflow.com/questions/59311942
复制相似问题