example_embedded_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // Copyright (c) 2011-2019 Canonical Ltd
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package yaml_test
  16. import (
  17. "fmt"
  18. "log"
  19. "gopkg.in/yaml.v3"
  20. )
  21. // An example showing how to unmarshal embedded
  22. // structs from YAML.
  23. type StructA struct {
  24. A string `yaml:"a"`
  25. }
  26. type StructB struct {
  27. // Embedded structs are not treated as embedded in YAML by default. To do that,
  28. // add the ",inline" annotation below
  29. StructA `yaml:",inline"`
  30. B string `yaml:"b"`
  31. }
  32. var data = `
  33. a: a string from struct A
  34. b: a string from struct B
  35. `
  36. func ExampleUnmarshal_embedded() {
  37. var b StructB
  38. err := yaml.Unmarshal([]byte(data), &b)
  39. if err != nil {
  40. log.Fatalf("cannot unmarshal data: %v", err)
  41. }
  42. fmt.Println(b.A)
  43. fmt.Println(b.B)
  44. // Output:
  45. // a string from struct A
  46. // a string from struct B
  47. }