golang反射小练习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28057541/article/details/78725526
package main

import (
    "fmt"
    "reflect"
    "strings"
)

type A struct {
    b string
    c string
    d string
}

func (a *A) GetB() string {
    return a.b
}

func (a *A) GetC() string {
    return a.c
}

func (a *A) GetD() string {
    return a.d
}

func main() {
    a := &A{}
    a.b = "we get b!"
    a.c = "we get c!"
    a.d = "we get d!"

    v := reflect.TypeOf(a).Elem()
    ac := reflect.ValueOf(a)

    for index:=0;index<v.NumField();index++{
        methodName := "Get"+strings.ToUpper(v.Field(index).Name)
        method := ac.MethodByName(methodName)
        c := method.Call(nil)
        result := c[0].String()
        fmt.Printf("%d: %s\n",index,result)
    }
}

运行结果

0: we get b!
1: we get c!
2: we get d!

参考链接(包看包会):

Go语言中反射包的实现原理

Go语言反射详解

猜你喜欢

转载自blog.csdn.net/qq_28057541/article/details/78725526
今日推荐