Bootstrap

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.NumField(); k++ {
                fmt.Printf("%s -- %v \n", t.Field(k).Name, v.Field(k).Interface())   
        }
}

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

;