空接口interface{},reflect配合空接口,让原本是静态类型的go具备了很多动态类型语言的特征。
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string
Age int
Id string
}
func (u User)sayHello() {
fmt.Println("hello!")
}
func main() {
u := User{Name:"mckee", Age:20, Id:"user100"};
t := reflect.TypeOf(u)
fmt.Println(t) //main.User
fmt.Println(t.Name()) //User
fmt.Println(t.NumField()) //3
fmt.Println(t.Kind()) //struct
//检测类型
if k := t.Kind(); k != reflect.Struct {
return
}
//输出所有的属性,结果如下:
/*
Name string mckee
Age int 20
Id string user100
*/
v := reflect.ValueOf(u)
for i := 0; i < t.NumField(); i++ {
fieldType := t.Field(i)
fmt.Println(fieldType.Name, fieldType.Type, v.Field(i).Interface())
}
//输出所有方法
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
fmt.Println(m.Name, m.Type) //sayHello func(main.User)
}
}
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string
Age int
Id string
}
func (u User)SayHello(name string) {
fmt.Println("hello, ", name, "! my name is ", u.Name)
}
func main() {
u := User{Name:"mckee", Age:20, Id:"user100"};
//hello, Jack ! my name is mckee
reflect.ValueOf(u).MethodByName("SayHello").Call([]reflect.Value{reflect.ValueOf("Jack")})
}