Go语言笔记:struct结构遍历

package main

import (
        "fmt"
        "reflect"
)

type User struct  {
        Id int
        Name string
        //addr string
}

func main(){
        u := User{Id:1001, Name:"xxx"/*, addr:"xxx"*/}
        t := reflect.TypeOf(u)
        v := reflect.ValueOf(u)
        for k := 0; k < t.NumFiled(); k++ {
                fmt.Printf("%s -- %v \n", t.Filed(k).Name, v.Field(k).Interface())   
        }
}


注:当结构体中含有非导出字段时,v.Field(k).Interface()会panic

posted @ 2018-11-21 15:21  xushukui  阅读(5890)  评论(0编辑  收藏  举报