github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/reflector/util_test.go (about) 1 package reflector 2 3 import ( 4 "fmt" 5 "image" 6 "reflect" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 type t int // A type definition 13 14 // Some methods on the type 15 func (r t) Twice() t { return r * 2 } 16 func (r t) Half() t { return r / 2 } 17 func (r t) Less(r2 t) bool { return r < r2 } 18 func (r t) privateMethod() {} // nolint unused 19 20 type FooService interface { 21 Foo1(x int) int 22 Foo2(x string) string 23 } 24 25 func TestListMethods(te *testing.T) { 26 report(t(0)) 27 report(image.Point{}) 28 report((*FooService)(nil)) 29 report(struct{ FooService }{}) 30 } 31 32 func report(x interface{}) { 33 v := reflect.ValueOf(x) 34 t := reflect.TypeOf(x) // or v.Type() 35 36 for t.Kind() == reflect.Ptr { 37 t = t.Elem() 38 } 39 40 n := t.NumMethod() 41 42 fmt.Printf("Type %v has %d exported methods:\n", t, n) 43 44 const format = "%-6s %-46s %s\n" 45 46 fmt.Printf(format, "Name", "Methods expression", "Methods value") 47 48 for i := 0; i < n; i++ { 49 if t.Kind() == reflect.Interface { 50 fmt.Printf(format, t.Method(i).Name, "(N/A)", t.Method(i).Type) 51 } else { 52 fmt.Printf(format, t.Method(i).Name, t.Method(i).Type, v.Method(i).Type()) 53 } 54 } 55 56 fmt.Println() 57 } 58 59 type MyMap map[string]interface{} 60 61 func TestMyMap(t *testing.T) { 62 v := reflect.ValueOf(MyMap(map[string]interface{}{})) 63 assert.Equal(t, reflect.Map, v.Type().Kind()) 64 }