golang 利用反射去遍历结构体
package main
import (
"fmt"
"reflect"
)
type ServerConfig struct {
Host
Port
}
// Conf 配置项主结构体
type Conf struct {
AppEnv string
Language string
Server *autoload.ServerConfig
Mysql *autoload.MysqlConfig
}
var (
Once sync.Once
Config = Conf{
AppEnv: "local",
Language: "zh_CN",
Server: &ServerConfig{
Host: "127.0.0.1",
Port: 9999,
},
}
)
func main(){
// 遍历结构体
t := reflect.TypeOf(Config)
v := reflect.ValueOf(Config)
for k := 0; k < t.NumField(); k++ {
// 判断是否指针类型
if kind := v.Field(k).Kind(); kind == reflect.Ptr {
// 判断是否结构体
if kind := v.Field(k).Elem().Kind(); kind == reflect.Struct {
fmt.Printf("%#v \n",v.Field(k).Interface())
}
}
}
}