mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(package): [slice] report unreadable struct fields (#401)
This commit is contained in:
1 parent
be3bc0c43f
commit
f525703d9f
2 files changed
+15
-3
No files matched your search
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user