Go Unmarshaling YAML into struct

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

Go Unmarshaling YAML into struct

问题

我正在尝试将一个YAML数据解析为字符串:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "gopkg.in/yaml.v2"
  6. )
  7. type Config struct {
  8. foo_bar string
  9. }
  10. func FailOnError(err error, msg string) {
  11. if err != nil {
  12. log.Fatalf("%s: %s", msg, err)
  13. panic(fmt.Sprintf("%s: %s", msg, err))
  14. }
  15. }
  16. func ParseYAMLConfig(data []byte) *Config {
  17. config := Config{}
  18. err := yaml.Unmarshal(data, &config)
  19. if err != nil {
  20. FailOnError(err, "Failed to unmarshal the config")
  21. }
  22. return &config
  23. }
  24. var configYAMLData = `
  25. ---
  26. foo_bar: "https://foo.bar"
  27. `
  28. func main() {
  29. config := ParseYAMLConfig([]byte(configYAMLData))
  30. fmt.Printf("%v", config)
  31. }

由于某种原因,config是一个空结构体&{}

英文:

I am trying to parse a YAML data into a string:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "gopkg.in/yaml.v2"
  6. )
  7. type Config struct {
  8. foo_bar string
  9. }
  10. func FailOnError(err error, msg string) {
  11. if err != nil {
  12. log.Fatalf("%s: %s", msg, err)
  13. panic(fmt.Sprintf("%s: %s", msg, err))
  14. }
  15. }
  16. func ParseYAMLConfig(data []byte) *Config {
  17. config := Config{}
  18. err := yaml.Unmarshal(data, &config)
  19. if err != nil {
  20. FailOnError(err, "Failed to unmarshal the config")
  21. }
  22. return &config
  23. }
  24. var configYAMLData = `
  25. ---
  26. foo_bar: "https://foo.bar"
  27. `
  28. func main() {
  29. config := ParseYAMLConfig([]byte(configYAMLData))
  30. fmt.Printf("%v", config)
  31. }

For some reason, config is an empty struct &{} though.

答案1

得分: 8

你的结构体字段是未导出的。请将它们导出,然后它们就可以正常工作了。

  1. type Config struct {
  2. FooBar string `yaml:"foo_bar"`
  3. }
英文:

Your struct's fields are unexported. Export them and it'll work.

  1. type Config struct {
  2. FooBar string `yaml:"foo_bar"`
  3. }

答案2

得分: 2

首字母大写很重要:

foo_bar --> Foo_bar

英文:

The capital matters:

foo_bar --> Foo_bar

huangapple
  • 本文由 发表于 2015年4月10日 00:35:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/29544146.html
匿名

发表评论

匿名网友

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

确定