Skip to content

Commit

Permalink
Distinguish between empty slice and nil slice
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW committed Feb 14, 2020
1 parent 61d0bc0 commit a8dfd39
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
6 changes: 5 additions & 1 deletion encode.go
Expand Up @@ -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 {
Expand Down
28 changes: 27 additions & 1 deletion encode_test.go
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
{
Expand Down

0 comments on commit a8dfd39

Please sign in to comment.