golang reflect简单使用

package main
 
import (
    "fmt"
    "reflect"
)
 
type MyStruct struct {
    name string
}
 
func (this *MyStruct) GetName() string {
    return this.name
}
 
func (this *MyStruct) SayName(name string) string {
    //fmt.Println(name)
    //return "hello", 2
    return name
}
 
func main() {
    s := "this is string"
    fmt.Println(reflect.TypeOf(s))
    fmt.Println(reflect.ValueOf(s))
    fmt.Println("-------------------")
 
    var x float64 = 3.4
    fmt.Println(reflect.TypeOf(x))
    fmt.Println(reflect.ValueOf(x))
    fmt.Println("-------------------")
 
    a := new(MyStruct)
    a.name = "fjgui"
    fmt.Println(reflect.ValueOf(a))
    fmt.Println(reflect.TypeOf(a))
 
    fmt.Println(reflect.TypeOf(a).NumMethod())
    b := reflect.ValueOf(a).MethodByName("GetName").Call([]reflect.Value{})
    fmt.Println(b[0])
    fmt.Println("-------------------")
 
    args := []reflect.Value{reflect.ValueOf("liming")}
    result := reflect.ValueOf(a).MethodByName("SayName").Call(args)
    if len(result) > 0 {
        for _, resp := range result {
            if resp.Interface() != nil {
                fmt.Println(resp.Interface())
            }
        }
    }
    fmt.Println(reflect.ValueOf(a).Elem().Field(0).String())
    fmt.Println(reflect.TypeOf(a).Elem().Field(0).Type)

 
}

D:/Go/bin/go.exe build -i [F:/GoProject/src/testreflect]

成功: 进程退出代码 0.

F:/GoProject/src/testreflect/testreflect.exe [F:/GoProject/src/testreflect]

string

this is string

-------------------

float64

3.4

-------------------

&{fjgui}

*main.MyStruct

2

fjgui

-------------------

liming

fjgui

string

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值