From a8dfd3908106f5328e0fec82a1b1f86364edcc60 Mon Sep 17 00:00:00 2001 From: k1LoW Date: Fri, 14 Feb 2020 10:36:33 +0900 Subject: [PATCH] Distinguish between empty slice and nil slice --- encode.go | 6 +++++- encode_test.go | 28 +++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/encode.go b/encode.go index 413942e..7567bba 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 && !value.IsNil() { + 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 06fcc26..e618952 100644 --- a/encode_test.go +++ b/encode_test.go @@ -189,7 +189,24 @@ func TestEncoder(t *testing.T) { }, }, }, - + { + "a: 1\nb:\n\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 {