Skip to content

Commit

Permalink
feat: MethodOf
Browse files Browse the repository at this point in the history
  • Loading branch information
Drelf2018 committed Dec 12, 2023
1 parent 9a4900a commit c17932f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Reflect/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,30 @@ func FieldOf(elem reflect.Type) []reflect.StructField {
return r
}

func MethodOf(value reflect.Value) map[reflect.Method]reflect.Value {
if value.Kind() != reflect.Struct && (value.Kind() != reflect.Ptr || value.Elem().Kind() != reflect.Struct) {
panic(ErrValue{value})
}
elem := value.Type()
r := make(map[reflect.Method]reflect.Value)
for i := elem.NumMethod() - 1; i >= 0; i-- {
r[elem.Method(i)] = value.Method(i)
}
return r
}

func MethodFuncOf(value reflect.Value) map[string]any {
if value.Kind() != reflect.Struct && (value.Kind() != reflect.Ptr || value.Elem().Kind() != reflect.Struct) {
panic(ErrValue{value})
}
elem := value.Type()
r := make(map[string]any)
for i := elem.NumMethod() - 1; i >= 0; i-- {
r[elem.Method(i).Name] = value.Method(i).Interface()
}
return r
}

type Reflect[V any] struct {
types map[uintptr][]V
Alias func(elem reflect.Type) []uintptr
Expand Down
20 changes: 20 additions & 0 deletions Reflect/reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package Reflect_test

import (
"fmt"
"reflect"
"testing"

"github.com/Drelf2018/TypeGo/Reflect"
Expand All @@ -26,6 +27,25 @@ type Struct1 struct {
} `ref:"Struct4"`
}

func (*Struct1) Test1(int) {}
func (Struct1) Test2(string) {}
func (*Struct1) Test3(bool) {}
func (Struct1) Test4(a, b int) float64 {
return float64(a + b)
}

func TestMethod(t *testing.T) {
s := reflect.ValueOf(Struct1{})
for name, fn := range Reflect.MethodFuncOf(s) {
switch fn.(type) {
case func(string):
fmt.Printf("string: %v\n", name)
case func(int, int) float64:
fmt.Printf("float64: %v\n", name)
}
}
}

func TestTag(t *testing.T) {
tag := Reflect.NewTagStruct("ref", Reflect.WithSlice[Reflect.Tag](Struct1{}))
v := tag.Get(&[]Struct1{})
Expand Down

0 comments on commit c17932f

Please sign in to comment.