1 package main
 2 
 3 
 4 import (
 5     "fmt"
 6     "reflect"
 7 )
 8 
 9 
10 func main() {
11    tonydon := &User{"TangXiaodong", 100, "0000123"}
12    object := reflect.ValueOf(tonydon)
13    myref := object.Elem()
14    typeOfType := myref.Type()
15    for i:=0; i<myref.NumField(); i++{
16        field := myref.Field(i)
17        fmt.Printf("%d. %s %s = %v \n", i, typeOfType.Field(i).Name, field.Type(), field.Interface())
18    }
19    tonydon.SayHello()
20    v := object.MethodByName("SayHello")
21    v.Call([]reflect.Value{})
22 }
23 
24 type User struct {
25     Name string
26     Age  int
27     Id   string
28 }
29 
30 
31 func (u *User) SayHello() {
32     fmt.Println("I'm " + u.Name + ", Id is " + u.Id + ". Nice to meet you! ")
33 }

编译运行结果如下:

0. Name string = TangXiaodong 
1. Age int = 100
2. Id string = 0000123 
I'm TangXiaodong, Id is 0000123. Nice to meet you! 
I'm TangXiaodong, Id is 0000123. Nice to meet you! 

 

 

 

相关文章:

  • 2019-01-01
  • 2021-08-10
  • 2021-05-04
  • 2022-12-23
  • 2022-02-20
猜你喜欢
  • 2022-12-23
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-10
  • 2022-12-23
相关资源
相似解决方案