定义
package main
import (
"fmt"
"reflect"
)
type user struct {
Id int
Name string
Age int
}
func (u user) Hello() {
fmt.Println("hello world")
}
func main() {
u := user{1, "cll", 12}
info(u)
}
func info(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println("type:" + t.Name())
v := reflect.ValueOf(o)
fmt.Println("fields:")
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
val := v.Field(i).Interface()
fmt.Printf("%6s:%v = %v\n", f.Name, f.Type, val)
}
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
fmt.Printf("%6s:%v\n", m.Name, m.Type)
}
}
参考:
https://studygolang.com/articles/2762
本文通过一个具体的Go语言示例,介绍了如何使用反射来获取结构体类型的信息,包括字段名、字段类型及其值,以及类型的方法等。此过程有助于深入理解Go语言中反射的用法。

被折叠的 条评论
为什么被折叠?



