英文:
Why does this TOML table not parse correctly in Go
问题
我对Golang相对较新。我一直在尝试解决这个问题,但没有找到任何帮助我解决问题的东西。我只是想将config.toml
文件解析到我的应用程序中。
我的config.toml
文件如下所示:
[[trees]]
name = "test1"
tags = ["main", "dev"]
[[trees]]
name = "test2"
tags = ["main", "dev", "prod"]
我用来读取文件的代码如下:
import (
"os"
"fmt"
toml "github.com/pelletier/go-toml/v2"
)
type Configuration struct {
Trees []tree `toml:"trees"`
}
type tree struct {
name string `toml:"name"`
tags []string `toml:"tags"`
}
func main() Configuration {
doc, e := os.ReadFile("config.toml")
if e != nil {
panic(e)
}
var cfg Configuration
err := toml.Unmarshal(doc, &cfg)
if err != nil {
panic(err)
}
fmt.Println(cfg.Trees)
return cfg
}
当我执行这段代码时,我得到了以下空数组作为输出:
> [{ []} { []}]
如果有人能告诉我我在这里做错了什么,我将非常感激。
英文:
I'm relatively new to Golang. I've been trying to solve this issue for a little while but have not found anything to help me. I am just trying to parse a config.toml
file into my application.
My config.toml
file is as follows:
[[trees]]
name = "test1"
tags = ["main", "dev"]
[[trees]]
name = "test2"
tags = ["main", "dev", "prod"]
And the code which I am using to read the file:
import (
"os"
"fmt"
toml "github.com/pelletier/go-toml/v2"
)
type Configuration struct {
Trees []tree `toml:"trees"`
}
type tree struct {
name string `toml:"name"`
tags []string `toml:"tags"`
}
func main() Configuration {
doc, e := os.ReadFile("config.toml")
if e != nil {
panic(e)
}
var cfg Configuration
err := toml.Unmarshal(doc, &cfg)
if err != nil {
panic(err)
}
fmt.Println(cfg.Trees)
return cfg
}
When I execute the code, I get the following empty array as an output:
> [{ []} { []}]
If anyone can tell me what I am doing wrong here, that would be much appreciated.
答案1
得分: 1
你需要将结构体字段名大写:
type Configuration struct {
Trees []tree `toml:"trees"`
}
type tree struct {
Name string `toml:"name"`
Tags []string `toml:"tags"`
}
这里有一个关于json.Marshal
的相关解释:结构体字段需要是公开的(即大写字母开头的名称)。
英文:
You need to capitalize the struct field names:
type Configuration struct {
Trees []tree `toml:"trees"`
}
type tree struct {
Name string `toml:"name"`
Tags []string `toml:"tags"`
}
Here's a related explanation for json.Marshal
: the structure fields need to be public (ie, uppercase names).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论