golang reflect简单使用
发布时间:2020-12-16 18:19:00 所属栏目:大数据 来源:网络整理
导读:package mainimport ("fmt""reflect")type MyStruct struct {name string}func (this *MyStruct) GetName() string {return this.name}func (this *MyStruct) SayName(name string) (string,int) {//fmt.Println(name)return "hello",2}func main() {s := "t
|
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,int) {
//fmt.Println(name)
return "hello",2
}
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())
}
}
}
}
C:/Go/bin/go.exe build -i [F:/Go/src/reflect] 成功: 进程退出代码 0. F:/Go/src/reflect/reflect.exe [F:/Go/src/reflect] string this is string ------------------- float64 3.4 ------------------- &{fjgui} *main.MyStruct 2 fjgui ------------------- hello 2 成功: 进程退出代码 0. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
