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 Marshaler support for slices of interfaces. #75

Open
wants to merge 1 commit into
base: main
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
14 changes: 14 additions & 0 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,20 @@ func (p *Encoder) marshal(val reflect.Value) cfValue {
}
}
return dict
case reflect.Interface, reflect.Ptr:
// Attempt to marshal the underlying type of the interface
if val.CanInterface() {
if inter := val.Interface(); inter != nil {
// Pointer to interface
interptr := reflect.New(reflect.TypeOf(inter))
// Elem requires an Interface or Pointer
if elem := interptr.Elem(); elem.IsValid() && elem.CanSet() {
elem.Set(reflect.ValueOf(inter))
return p.marshal(reflect.Indirect(interptr))
}
}
}
panic(&unknownTypeError{typ})
default:
panic(&unknownTypeError{typ})
}
Expand Down
30 changes: 30 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,33 @@ func TestInterfaceFieldMarshal(t *testing.T) {
t.Log("expect non-zero data")
}
}

type Dog struct {
Name string
}

type Animal interface{}

func TestInterfaceSliceMarshal(t *testing.T) {
x := make([]Animal, 0)
x = append(x, &Dog{Name: "dog"})

b, err := Marshal(x, XMLFormat)
if err != nil {
t.Error(err)
} else if len(b) == 0 {
t.Error("expect non-zero data")
}
}

func TestInterfaceGeneralSliceMarshal(t *testing.T) {
x := make([]interface{}, 0) // accept any type
x = append(x, &Dog{Name: "dog"}, "a string", 1, true)

b, err := Marshal(x, XMLFormat)
if err != nil {
t.Error(err)
} else if len(b) == 0 {
t.Error("expect non-zero data")
}
}