golang 反射结构字段类型

前端之家收集整理的这篇文章主要介绍了golang 反射结构字段类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


golang 反射用法,做个笔记.

package main

import (
	"fmt"
	"reflect"
)

type roles struct {
	roleId   int
	roleName string
}
type User struct {
	Name     string
	Age      int
	Email    string
	NickName string
	Telphone int
	Roles    roles
}

func main() {
	u := User{Name: "Name",Age: 30,Email: "xxxx@afanty3d.com",NickName: "omni360",Telphone: xxxxx,Roles: roles{roleId: 1001,roleName: "administrator"}}
	fmt.Println(u)
	Info(u)

}

func Info(o interface{}) {
	t := reflect.TypeOf(o)
	fmt.Println("Type:",t.Name())

	v := reflect.ValueOf(o)
	fmt.Println("Fileds:")
	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)

	}
}

猜你在找的Go相关文章