这可以在golang中实现吗?

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

Is it possible to do this in golang?

问题

我对golang中的.yaml文件有一个疑问,假设我有一个包含以下内容的.yaml文件:

print:
  1

print:
  2

print:
  3

有没有办法获取yaml文件中的所有print?在golang中如何表示这种结构?例如,如果我在一个.yaml文件中有以下内容:

print:
  1

在golang中,我可以这样表示它:

type Print struct {
  Print int `yaml:"print"`
}

如果无法这样做,还有其他类似的方法吗?提前谢谢。

英文:

I have a doubt about the .yaml files in golang, suppose I have a .yaml file with the following content:

print:
  1

print:
  2

print:
  3

Is there a way to get all the print in the yaml file? How would I represent that structure in golang? Because for example if I have this in a .yaml file:

print:
  1

In golang I can represent it like this:

type Print struct {
  Print int `yaml:"print"`
}

And if that cannot be done, what other way would there be to do something similar? Thanks in advance.

答案1

得分: 6

你的YAML不合法。在映射中,不能有相同的键出现多次。根据规范的3.2.1.1节

映射节点的内容是一组无序的键/值节点对,限制条件是每个键都是唯一的

相反,你可以使用映射到序列的方式。

print: [1,2,3]

并将其存储为[]int类型。

type Print struct {
  Print []int `yaml:"print"`
}
英文:

Your YAML is not legal. You can't have the same key multiples times in a mapping. From 3.2.1.1 of the spec...

> The content of a mapping node is an unordered set of key/value node pairs, with the restriction that each of the keys is unique.

Instead, use a mapping to a sequence.

print: [1,2,3]

And store it as an []int.

type Print struct {
  Print []int `yaml:"print"`
}

huangapple
  • 本文由 发表于 2022年9月24日 04:30:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/73832691.html
匿名

发表评论

匿名网友

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

确定