• 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)
        }
    
    }
  • 相关阅读:
    python之路-HTML初识
    python之路-CentOS6.5 安装Python 的依赖包
    python之路-离线pip下载Python包
    python之路-Memcache
    python之路-SQLAlchemy
    python之路-Redis
    python之路-Mysql
    偶然发现了获取有ID的dom的一种方法
    js 工厂模式和构造函数的区别
    ES6:export和import
  • 原文地址:https://www.cnblogs.com/aqgy12138/p/15687198.html
Copyright © 2020-2023  润新知