为什么这个 TOML 表在 Go 中无法正确解析?

huangapple go评论88阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2022年10月23日 02:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/74166038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定