GO之旅(3)

来源:互联网 发布:西门子工控淘宝旗舰店 编辑:程序博客网 时间:2024/05/17 23:05

package mainimport ("fmt""reflect")type User struct {Id   intName stringAge  int}func (u User) Hello() {fmt.Println("hello world.")}func main() {u := User{1, "OK", 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)}}
输出为:


由接口反射(reflection)出对象的相关信息,包括方法,内部变量等等



原创粉丝点击