1. 程式人生 > 其它 >golang 通過反射獲取結構體欄位值,以及欄位為結構體型別的欄位。

golang 通過反射獲取結構體欄位值,以及欄位為結構體型別的欄位。

直接上程式碼,初略的寫了一下,具體使用按照自身邏輯改改。

package main

import (
    "fmt"
    "reflect"
)

type Student struct {

    Class string

    School string

    Love string

    StudentBase
}

type StudentBase struct {
    Name string
    Age  int
}

func main() {

    var student Student

    student.Class = "三年一班"
student.School = "附屬小學" student.Love = "閱讀、遊戲" student.Name = "李華" student.Age = 8 t := reflect.TypeOf(student) if t.Kind() == reflect.Ptr { t = t.Elem() } for i := 0; i < t.NumField(); i++ { fieldName := t.Field(i).Name //struct 欄位 if
fieldName == "StudentBase" { fmt.Println("Struct Property StudentBase") child := t.Field(i).Type if child.Kind() == reflect.Struct { for j := 0; j < child.NumField(); j++ { jFieldName := child.Field(j).Name jFieldValue :
= reflect.ValueOf(student.StudentBase).FieldByName(jFieldName) fmt.Println("name:", jFieldName, "value:", jFieldValue) } continue } } fieldValue := reflect.ValueOf(student).FieldByName(fieldName) fmt.Println("name:", fieldName, "value:", fieldValue) } }