From 0977624c8b20d1a4a78a3005a151aead0a4ee7cb Mon Sep 17 00:00:00 2001 From: John Pedrie Date: Tue, 13 Aug 2024 13:06:09 -0400 Subject: [PATCH 1/2] replace strict field type check with AssignableTo --- reflections.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reflections.go b/reflections.go index 6ca21c7..d3c457d 100644 --- a/reflections.go +++ b/reflections.go @@ -141,8 +141,8 @@ func SetField(obj interface{}, name string, value interface{}) error { structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) - if structFieldType != val.Type() { - invalidTypeError := fmt.Errorf("provided value type didn't match obj field type") + if !val.Type().AssignableTo(structFieldType) { + invalidTypeError := fmt.Errorf("provided value type not assignable to obj field type") return invalidTypeError } From 846ede2ad6e0e2e8d7569e58eb67ce477bb2ec47 Mon Sep 17 00:00:00 2001 From: John Pedrie Date: Tue, 13 Aug 2024 13:12:47 -0400 Subject: [PATCH 2/2] add test --- reflections_test.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/reflections_test.go b/reflections_test.go index c601594..badf693 100644 --- a/reflections_test.go +++ b/reflections_test.go @@ -619,3 +619,23 @@ func TestFields_deep(t *testing.T) { assert.Equal(t, fieldsDeep[1], "Street") assert.Equal(t, fieldsDeep[2], "Number") } + +type SingleString string + +type StringList []string + +type Bar struct { + A StringList +} + +func TestAssignable(t *testing.T) { + var b Bar + expected := []string{"a", "b", "c"} + assert.Nil(t, SetField(&b, "A", expected)) + assert.Equal(t, StringList(expected), b.A) + + err := SetField(&b, "A", []int{0, 1, 2}) + assert.NotNil(t, err) + assert.Equal(t, "provided value type not assignable to obj field type", + err.Error()) +}