go 遍历结构体 | 臭大佬
简介
go 遍历结构体
代码如下
package main
import (
"fmt"
"reflect"
)
type Tags struct {
ID int
Name string
}
func main() {
var tag Tags
tag.ID = 1
tag.Name = "魏花花"
var typeInfo = reflect.TypeOf(tag)
var valInfo = reflect.ValueOf(tag)
num := typeInfo.NumField()
for i := 0; i < num; i++ {
key := typeInfo.Field(i).Name
val := valInfo.Field(i).Interface()
fmt.Println(i)
fmt.Printf("%T --- %v\n", key, key)
fmt.Printf("%T --- %v\n", val, val)
}
}
~:go run index.go
0
string —- ID
int —- 1
1
string —- Name
string —- 魏花花