go 结构体反射reflect

package main
import (
	"fmt"
	"reflect"
)
type S struct {
	A int
	B string
}
func (s *S) Test() {
	fmt.Println("this is a test")
}
func main() {
	a:= "12345678-1234-5678-1234-567812345678"
	fmt.Println("++++++++++++++++++",len(a))
	s := S{23, "skidoo"}
	v := reflect.ValueOf(&s)
	t := v.Type()
	fmt.Printf("00 v: %#v,t: %#v\n", v,t)
	v.Elem().Field(0).SetInt(100)
	fmt.Printf("01 v: %#v,t: %#v\n", v,t)
	fmt.Println("method num:", v.NumMethod())
	for i := 0; i < v.NumMethod(); i++ {
		f := t.Method(i)
		fmt.Printf("%d method, name:%v, type:%v \n", i, f.Name, f.Type)
		fmt.Printf("func:%#v\n", f)
	}
}

输出:

++++++++++++++++++ 36
00 v: &main.S{A:23, B:"skidoo"},t: &reflect.rtype{size:0x8, ptrdata:0x8, hash:0x5241b518, tflag:0x9, align:0x8, fieldAlign:0x8, kind:0x36, equal:(func(unsafe.Pointer, unsafe.Pointer) bool)(0x4033a0), gcdata:(*uint8)(0x526358), s
tr:4998, ptrToThis:0}
01 v: &main.S{A:100, B:"skidoo"},t: &reflect.rtype{size:0x8, ptrdata:0x8, hash:0x5241b518, tflag:0x9, align:0x8, fieldAlign:0x8, kind:0x36, equal:(func(unsafe.Pointer, unsafe.Pointer) bool)(0x4033a0), gcdata:(*uint8)(0x526358),
str:4998, ptrToThis:0}
method num: 1
0 method, name:Test, type:func(*main.S)
func:reflect.Method{Name:"Test", PkgPath:"", Type:(*reflect.rtype)(0xc000042060), Func:reflect.Value{typ:(*reflect.rtype)(0xc000042060), ptr:(unsafe.Pointer)(0xc000006048), flag:0x13}, Index:0
posted @ 2022-03-19 18:15  ty1539  阅读(54)  评论(0编辑  收藏  举报