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)
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM