看看这个例子:
package main
import (
"fmt"
"log"
yaml "gopkg.in/yaml.v2"
)
type T struct {
Bar string `yaml:"bar,omitempty"`
Pint string `yaml:"pint,omitempty"`
}
func main() {
var t = make([]T, 3)
t[0].Bar = "hello"
t[1].Bar = "another"
t[1].Pint = "guiness"
t[2].Bar = "second"
y, err := yaml.Marshal(t)
if err != nil {
log.Fatalf("Marshal: %v", err)
}
fmt.Println(string(y))
}
输出:
- bar: hello
- bar: another
pint: guiness
- bar: second
如果您想在您想要的输出中保持空字符串,那么您可以这样做
package main
import (
"fmt"
"log"
yaml "gopkg.in/yaml.v2"
)
type S string
func (s *S) IsZero() bool {
return false
}
type T struct {
Bar string `yaml:"bar,omitempty"`
Pint *S `yaml:"pint,omitempty"`
}
func main() {
var t = make([]T, 3)
t[0].Bar = "hello"
t[1].Bar = "another"
p1 := S("guiness")
t[1].Pint = &p1
t[2].Bar = "second"
p2 := S("")
t[2].Pint = &p2
y, err := yaml.Marshal(t)
if err != nil {
log.Fatalf("Marshal: %v", err)
}
fmt.Println(string(y))
}
输出:
- bar: hello
- bar: another
pint: guiness
- bar: second
pint: ""
有关yaml软件包的更多信息:
https://godoc.org/gopkg.in/yaml.v2