Go 反射:结构体与函数的深入探索
1. 处理嵌套字段
在 Go 中,结构体字段的索引由其在源代码中定义的顺序决定。例如,以下输出展示了 Total 字段的索引为 2:
Field [2]: Name: Total, Type: float64, Exported: true
当检查嵌套结构体字段时,情况会变得更加复杂。以下代码展示了如何递归检查嵌套结构体字段:
package main
import (
"reflect"
// "strings"
// "fmt"
)
func inspectStructs(structs ...interface{}) {
for _, s := range structs {
structType := reflect.TypeOf(s)
if (structType.Kind() == reflect.Struct) {
inspectStructType([]int {}, structType)
}
}
}
func inspectStructType(baseIndex []int, structType reflect.Type) {
Printfln("--- Struct Type: %v", structType)
for i := 0; i < structType.NumField(); i++ {
超级会员免费看
订阅专栏 解锁全文

134

被折叠的 条评论
为什么被折叠?



