move embedded struct example into godoc

Examples are nicer when they're shown in the godoc.
This commit is contained in:
Roger Peppe 2017-07-21 10:26:57 +01:00
Родитель 835086a6b6
Коммит d56ec34a3d
2 изменённых файлов: 41 добавлений и 35 удалений

41
example_embedded_test.go Normal file
Просмотреть файл

@ -0,0 +1,41 @@
package yaml_test
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
// An example showing how to unmarshal embedded
// structs from YAML.
type StructA struct {
A string `yaml:"a"`
}
type StructB struct {
// Embedded structs are not treated as embedded in YAML by default. To do that,
// add the ",inline" annotation below
StructA `yaml:",inline"`
B string `yaml:"b"`
}
var data = `
a: a string from struct A
b: a string from struct B
`
func ExampleUnmarshal_embedded() {
var b StructB
err := yaml.Unmarshal([]byte(data), &b)
if err != nil {
log.Fatal("cannot unmarshal data: %v", err)
}
fmt.Println(b.A)
fmt.Println(b.B)
// Output:
// a string from struct A
// a string from struct B
}

Просмотреть файл

@ -1,35 +0,0 @@
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
type StructA struct {
A string `yaml:"a"`
}
type StructB struct {
// go-yaml will not decode embedded structs by default, to do that
// you need to add the ",inline" annotation below
StructA `yaml:",inline"`
B string `yaml:"b"`
}
var data = `
a: a string from struct A
b: a string from struct B
`
func main() {
var b StructB
err := yaml.Unmarshal([]byte(data), &b)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Println(b.A)
fmt.Println(b.B)
}