After the updates to gopkg.in itself, it’s time for gopkg.in/yaml.v2 to receive some attention. The following improvements are now available in the yaml package:
Support for omitempty on struct values
The omitempty attribute can now be used in tags of fields with a struct type. In those cases, the given field and its value only become part of the generated yaml document if one or more of the fields exported by the field type contain non-empty values, according to the usual conventions for omitempty .
For instance, considering these two types:
type TypeA struct {
Maybe TypeB `yaml:",omitempty"`
}
type TypeB struct {
N int
}
the yaml package would only serialize the Maybe mapping into the generated yaml document if its N field was non-zero.
Support for inlined maps
The yaml package was previously able to handle the inlining of structs. For example, in the following snippet TypeB would be handled as if its fields were part of TypeA during serialization or deserialization:
type TypeA struct {
Field TypeB `yaml:",inline"`
}
This convention for inlining differs from the standard json package, which inlines anonymous fields instead of considering such an attribute. That difference is mainly historical: the base of the yaml package was copied from mgo’s bson package, which had this convention before the standard json package supported any inlining at all.
Now the support for inlining maps, previously available in the bson package, is also being copied over. In practice, it allows unmarshaling a yaml document such as
a: 1
b: 2
c: 3
into a type that looks like
type T struct {
A int
Rest map[string]int `yaml:",inline"`
}
and obtaining in the resulting Rest field the value map[string]int{“b”: 2, “c”: 3} , while field A is set to 1 as usual. Serializing out that resulting value would reverse the process, and generate the original document including the extra fields.
That’s a convenient way to read documents with a partially known structure and manipulating them in a non-destructive way.
Bug fixes
A few problems were also fixed in this release. Most notably:
-
A spurious error was reported when custom unmarshalers handled errors internally by retrying. Reported a few times and fixed by Brian Bland.
-
An empty yaml list ([]) is now decoded into a struct field as an empty slice instead of a nil one. Reported by Christian Neumann.
-
Unmarshaling into a struct with a slice field would append to it instead of overwriting. Reported by Dan Kinder.
-
Do not use TextMarshaler interface on types that implement yaml.Getter. Reported by Sam Ghods.