diff --git a/slice/field_read_test.go b/slice/field_read_test.go new file mode 100644 index 0000000..b0aead6 --- /dev/null +++ b/slice/field_read_test.go @@ -0,0 +1,11 @@ +package slice + +import "testing" + +func TestUniqueByFieldUnreadableInputs(t *testing.T) { + for _, input := range []any{nil, struct{ hidden string }{"value"}} { + if _, err := UniqueByField([]any{input}, "hidden"); err == nil { + t.Errorf("expected an error for %T", input) + } + } +} diff --git a/slice/slice.go b/slice/slice.go index 632afcf..0a8611f 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -949,10 +949,8 @@ func UniqueByField[T any](slice []T, field string) ([]T, error) { func getField[T any](item T, field string) (interface{}, error) { v := reflect.ValueOf(item) - t := reflect.TypeOf(item) - if t.Kind() == reflect.Ptr { - t = t.Elem() + if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { @@ -963,6 +961,9 @@ func getField[T any](item T, field string) (interface{}, error) { if !f.IsValid() { return nil, fmt.Errorf("field name %s not found", field) } + if !f.CanInterface() { + return nil, fmt.Errorf("field name %s is not exported", field) + } return v.FieldByName(field).Interface(), nil }