Skip to content

Commit

Permalink
Merge pull request #22 from jdpedrie/set-field-assignable
Browse files Browse the repository at this point in the history
replace strict field type check with AssignableTo
  • Loading branch information
oleiade authored Aug 24, 2024
2 parents 7387801 + 846ede2 commit b46dfad
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
4 changes: 2 additions & 2 deletions reflections.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Check failure on line 145 in reflections.go

View workflow job for this annotation

GitHub Actions / Build

fmt.Errorf can be replaced with errors.New (perfsprint)
return invalidTypeError
}

Expand Down
20 changes: 20 additions & 0 deletions reflections_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Check failure on line 631 in reflections_test.go

View workflow job for this annotation

GitHub Actions / Build

Function TestAssignable missing the call to method parallel
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())
}

0 comments on commit b46dfad

Please sign in to comment.