golang reflect

package main

import (
    "fmt"
    "reflect"
)

type Monster struct {
    Name  string `json:"name"`
    Age   int    `json:"monster_age"`
    Score float32
    Sex   string
}

func (s Monster) Print() {
    fmt.Println("--------start--------")
    fmt.Println(s)
    fmt.Println("--------end---------")
}

func (s Monster) GetSum(n1, n2 int) int {
    return n1 + n2
}

func (s Monster) Set(name string, age int, score float32, sex string) {
    s.Name = name
    s.Age = age
    s.Score = score
    s.Sex = sex
}

func TestStruct(a interface{}) {
    typ := reflect.TypeOf(a)
    val := reflect.ValueOf(a)
    kd := val.Kind()
    if kd != reflect.Struct {
        fmt.Println("except struct")
        return
    }
    num := val.NumField()
    fmt.Println("struct has field", num)
    for i := 0; i < num; i++ {
        fmt.Println("struct:", i, " field:", val.Field(i))
        // 获取tag
        tagVal := typ.Field(i).Tag.Get("json")
        if tagVal != "" {
            fmt.Println("struct:", i, " tag:", tagVal)
        }
    }
    numOfMethod := val.NumMethod()
    fmt.Println("struct method count:", numOfMethod)
    val.Method(1).Call(nil)
    // 调用结构体的第1个方法(按方法名称ASCII排序的)
    var params []reflect.Value
    params = append(params, reflect.ValueOf(10))
    params = append(params, reflect.ValueOf(40))
    res := val.Method(0).Call(params)
    fmt.Println("call 0 result:", res[0].Int())
}

func main() {
    var a Monster = Monster{
        Name:  "hhh",
        Age:   400,
        Score: 30.3,
    }
    TestStruct(a)
}