1. 程式人生 > >Go語言筆記:struct結構遍歷

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