diff --git a/encode.go b/encode.go index 413942eb..ddd307e4 100644 --- a/encode.go +++ b/encode.go @@ -231,7 +231,11 @@ func (e *Encoder) encodeBool(v bool) ast.Node { } func (e *Encoder) encodeSlice(value reflect.Value) (ast.Node, error) { - sequence := ast.Sequence(token.New("-", "-", e.pos(e.column)), e.isFlowStyle) + isFlowStyle := e.isFlowStyle + if value.Len() == 0 { + isFlowStyle = true + } + sequence := ast.Sequence(token.New("-", "-", e.pos(e.column)), isFlowStyle) for i := 0; i < value.Len(); i++ { node, err := e.encodeValue(value.Index(i), e.column) if err != nil { diff --git a/encode_test.go b/encode_test.go index 06fcc26d..90978107 100644 --- a/encode_test.go +++ b/encode_test.go @@ -189,7 +189,24 @@ func TestEncoder(t *testing.T) { }, }, }, - + { + "a: 1\nb: []\n", + struct { + A int + B []string + }{ + 1, ([]string)(nil), + }, + }, + { + "a: 1\nb: []\n", + struct { + A int + B []string + }{ + 1, []string{}, + }, + }, { "a: b\nc: d\n", struct { @@ -265,6 +282,15 @@ func TestEncoder(t *testing.T) { B float64 `yaml:"b,omitempty"` }{1, 0}, }, + { + "a: 1\n", + struct { + A int + B []string `yaml:"b,omitempty"` + }{ + 1, []string{}, + }, + }, // Flow flag {