Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix json error when struct field is slice and is nil #142

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
}

if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice && fromType.ConvertibleTo(toType) {
// if both from and to slices are nil, do nothing
if to.IsNil() && from.IsNil() {
return
}
if to.IsNil() {
slice := reflect.MakeSlice(reflect.SliceOf(to.Type().Elem()), from.Len(), from.Cap())
to.Set(slice)
Expand Down
34 changes: 34 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package copier_test

import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"reflect"
Expand Down Expand Up @@ -1611,6 +1612,39 @@ func TestDeepCopySimpleTime(t *testing.T) {
}
}

func TestDeepCopyWithNilByteSlices(t *testing.T) {
type From struct {
Flags json.RawMessage
}

type To struct {
Flags json.RawMessage
}

from := From{}
to := To{}

err := copier.CopyWithOption(&to, &from, copier.Option{
DeepCopy: true,
})
if err != nil {
t.Error("error when copying")
}
if to.Flags != nil {
t.Error("Flags byte array is not nil", to.Flags, from.Flags)
}

_, err = json.Marshal(from)
if err != nil {
t.Error("error when marshalling from struct")
}

_, err = json.Marshal(to)
if err != nil {
t.Error("error when marshalling from struct")
}
}

type TimeWrapper struct{
time.Time
}
Expand Down