参考
https://www.cnblogs.com/jiujuan/p/17142703.html
float反射示例
package main
import (
"fmt"
"reflect"
)
func main() {
var x float64 = 1.2345
fmt.Println("==TypeOf==")
t := reflect.TypeOf(x)
fmt.Println("type: ", t)
fmt.Println("kind:", t.Kind())
fmt.Println("==ValueOf==")
v := reflect.ValueOf(x)
fmt.Println("value: ", v)
fmt.Println("type:", v.Type())
fmt.Println("kind:", v.Kind())
fmt.Println("value:", v.Float())
fmt.Println(v.Interface())
fmt.Printf("value is %5.2e\n", v.Interface())
y := v.Interface().(float64)
fmt.Println(y)
fmt.Println("===kind===")
type MyInt int
var m MyInt = 5
v = reflect.ValueOf(m)
fmt.Println("kind:", v.Kind()) // Kind() 返回底层的类型 int
fmt.Println("type:", v.Type()) // Type() 返回类型 MyInt
}
struct反射示例
package main
import (
"fmt"
"reflect"
)
type student struct {
Name string `json:"name"`
Age int `json:"age" id:"1"`
}
func main() {
stu := student{
Name: "hangmeimei",
Age: 15,
}
valueOfStu := reflect.ValueOf(stu)
// 获取struct字段数量
fmt.Println("NumFields: ", valueOfStu.NumField())
// 获取字段 Name 的值
fmt.Println("Name value: ", valueOfStu.Field(0).String(), ", ", valueOfStu.FieldByName("Name").String())
// 字段类型
fmt.Println("Name type: ", valueOfStu.Field(0).Type())
typeOfStu := reflect.TypeOf(stu)
for i := 0; i < typeOfStu.NumField(); i++ {
// 获取字段名
name := typeOfStu.Field(i).Name
fmt.Println("Field Name: ", name)
// 获取tag
if fieldName, ok := typeOfStu.FieldByName(name); ok {
tag := fieldName.Tag
fmt.Println("tag-", tag, ", ", "json:", tag.Get("json"), ", id", tag.Get("id"))
}
}
}
标签:反射,Name,fmt,golang,tag,reflect,Println,type
From: https://www.cnblogs.com/liujitao79/p/17732088.html