示例1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package main import "fmt" import "reflect" type st struct { age int name string } func (_ st) Echo(str string) { fmt.Printf("echo(%s)\n", str) } func (_ *st) Echo2(str string) { fmt.Printf("echo2(%s)\n", str) } func main() { s := st{age: 18, name: "john"} p := reflect.ValueOf("halloo") v := reflect.ValueOf(s) v2 := reflect.ValueOf(&s) // 调用st结构体的方法 v.MethodByName("Echo").Call([]reflect.Value{p}) // 我们需要调用的是实体结构体指针的方法,注意v2与v2的区别,以及方法定义的区别 v2.MethodByName("Echo2").Call([]reflect.Value{p}) // 调用结构体的属性 fmt.Println(v.FieldByName("name")) } |