fix(package): [slice] report unreadable struct fields (#401)

This commit is contained in:
Yusuf Efe authored and GitHub committed 2026-10-22 10:39:00 +08:00
1 parent be3bc0c43f
commit f525703d9f
2 files changed
+15 -3

No files matched your search

+11
View File
@@ -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)
}
}
}
+4 -3
View File
@@ -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
}