reflect: Add FieldByNameFunc

This adds FieldByNameFunc, which some libraries like reflect2 need.

For my usecase I could also just stub FieldByNameFunc to panic, but
figured that it would work OK to just make it work. I'm not sure if
the overhead to FieldByName using a closure is acceptable.

Signed-off-by: Tyler Rockwood <rockwood@redpanda.com>
This commit is contained in:
Tyler Rockwood
2023-06-22 15:23:19 -05:00
committed by Ron Evans
parent dd4e9e86e7
commit fdc4bbbfad
3 changed files with 48 additions and 5 deletions
+11
View File
@@ -4,6 +4,7 @@ import (
"encoding/base64"
. "reflect"
"sort"
"strings"
"testing"
)
@@ -452,10 +453,20 @@ func TestTinyStruct(t *testing.T) {
t.Errorf("StrucTag for Foo=%v, want %v", got, want)
}
q, ok = reffb.FieldByNameFunc(func(s string) bool { return strings.ToLower(s) == "bar" })
if q.Name != "Bar" || !ok {
t.Errorf("FieldByNameFunc(bar)=%v,%v, want Bar, true", q.Name, ok)
}
q, ok = reffb.FieldByName("Snorble")
if q.Name != "" || ok {
t.Errorf("FieldByName(Snorble)=%v,%v, want ``, false", q.Name, ok)
}
q, ok = reffb.FieldByNameFunc(func(s string) bool { return strings.ToLower(s) == "snorble" })
if q.Name != "" || ok {
t.Errorf("FieldByName(snorble)=%v,%v, want ``, false", q.Name, ok)
}
}
func TestTinyZero(t *testing.T) {