example_embedded_test.go 712 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package yaml_test
  2. import (
  3. "fmt"
  4. "log"
  5. "gopkg.in/yaml.v2"
  6. )
  7. // An example showing how to unmarshal embedded
  8. // structs from YAML.
  9. type StructA struct {
  10. A string `yaml:"a"`
  11. }
  12. type StructB struct {
  13. // Embedded structs are not treated as embedded in YAML by default. To do that,
  14. // add the ",inline" annotation below
  15. StructA `yaml:",inline"`
  16. B string `yaml:"b"`
  17. }
  18. var data = `
  19. a: a string from struct A
  20. b: a string from struct B
  21. `
  22. func ExampleUnmarshal_embedded() {
  23. var b StructB
  24. err := yaml.Unmarshal([]byte(data), &b)
  25. if err != nil {
  26. log.Fatalf("cannot unmarshal data: %v", err)
  27. }
  28. fmt.Println(b.A)
  29. fmt.Println(b.B)
  30. // Output:
  31. // a string from struct A
  32. // a string from struct B
  33. }