我想用反射提取结构的映射成员的标签,而我发现如果从 MapIndex 检索成员的值,它的类型将被识别为“*接口{}”因此所有类型信息都丢失,没有提到反射可以提取细节信息。
package main
import (
"fmt"
"reflect"
)
type Student struct {
Sname string `MyTag:"student-name"`
}
type Teacher struct {
Name string `MyTag:"teacher-name"`
Students map[string]Student `MyTag:"teacher-students"`
}
var sam = Teacher{
Name: "Sam",
Students: map[string]Student{
"Sen": {
Sname: "Sen",
},
},
}
func traversalTag(obj interface{}) {
theType := reflect.TypeOf(obj)
fmt.Printf("Traversal tag with obj: type %v, value %v\n", theType.String(), obj)
elem := reflect.TypeOf(obj).Elem()
for i := 0; i < elem.NumField(); i++ {
fmt.Printf("Tag name %s, value %s\n", elem.Field(i).Name, elem.Field(i).Tag)
}
}
func tryMapWithType(students map[string]Student) {
for key, theValue := range students {
fmt.Printf("Key: %v, Value: %v, value pointer %p\n", key, theValue, &theValue)
traversalTag(&theValue)
}
}
func tryMapWithReflect(obj interface{}) {
reflectMap := reflect.ValueOf(obj)
for _, key := range reflectMap.MapKeys() {
theValue := reflectMap.MapIndex(key).Interface()
fmt.Printf("Key: %v, Value: %v, value pointer %p\n", key, theValue, &theValue)
traversalTag(&theValue) // Will have error
}
}
func main() {
tryMapWithType(sam.Students)
tryMapWithReflect(sam.Students)
}
运行后出现以下错误:
Starting: C:\Users\Mento\go\bin\dlv.exe dap --check-go-version=false --listen=127.0.0.1:50308 from d:\Coding\Golang\demo
DAP server listening at: 127.0.0.1:50308
Key: Sen, Value: {Sen}, value pointer 0xc000044230
Traversal tag with obj: type *main.Student, value &{Sen}
Tag name Sname, value MyTag:"student-name"
Key: Sen, Value: {Sen}, value pointer 0xc0000442c0
Traversal tag with obj: type *interface {}, value 0xc0000442c0
panic: reflect: NumField of non-struct type interface {}
谁能提示如何使用原始类型信息获取地图成员的指针?
HUX布斯
相关分类