(转) golang 中使用 reflect 获取结构中的字段和值

声明:内容源自网络,版权归原作者所有。若有侵权请在网页聊天中联系我

原址:https://blog.csdn.net/qq_40422846/article/details/87536312

package main

import (
   "reflect"
   "fmt"
)

type User struct {
   Id int
   Name string
   Age int
}

func main() {
   u := User{1,"xiaozhi",26}
   info(u)
}

func info(i interface{}) {
   t := reflect.TypeOf(i)
   fmt.Println("Type: ", t.Name())
   v := reflect.ValueOf(i)
   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)
   }
}

输出结果

Type:  User
Fields: 
    Id: int = 1
  Name: string = xiaozhi
   Age: int = 26

相关文章