我想用reflect提取struct的map成員標簽,而我發現如果從MapIndex中檢索成員的值,它的型別將被識別為“*interface{}”,因此所有型別資訊都丟失了,沒有提到reflect可以提取細節資訊。
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 {}
goroutine 1 [running]:
reflect.(*rtype).NumField(0xec2d20)
C:/Program Files/Go/src/reflect/type.go:1015 0xc8
main.traversalTag({0xebd9e0, 0xc0000442c0})
d:/Coding/Golang/demo/demo.go:31 0x1cb
main.tryMapWithReflect({0xec3d40, 0xc00007a480})
d:/Coding/Golang/demo/demo.go:48 0x2c9
main.main()
d:/Coding/Golang/demo/demo.go:54 0x38
Process 8716 has exited with status 2
dlv dap (11448) exited with code: 0
誰能暗示如何使用原始型別資訊獲取地圖成員的指標?
謝謝你,門托
uj5u.com熱心網友回復:
如您所知,使用&theValue決議為 type *interface{}。該型別與您傳遞給from*interface{}的型別不同。*StudenttraversalTagtryMapWithType
如果要傳遞*Student給traversalTagfrom tryMapWithReflect,則需要使用反射創建該指標值。簡單的原生 Go 地址運算子&是不夠的。
當您有一個reflect.Value可尋址的時,您需要做的就是呼叫該.Addr()方法以獲取指向可尋址值的指標,但是映射元素不可尋址,因此reflectMap.MapIndex(key)不可尋址。所以,不幸的是,你不可能reflectMap.MapIndex(key).Addr().Interface()得到*Student.
因此,您唯一的選擇是使用反射來創建該*Student型別的新值,將指向的值設定為映射中的值,然后回傳該.Interface()值。
func tryMapWithReflect(obj interface{}) {
reflectMap := reflect.ValueOf(obj)
for _, key := range reflectMap.MapKeys() {
theValue := reflectMap.MapIndex(key).Interface()
// allocate a new value of type *Student
newValue := reflect.New(reflectMap.MapIndex(key).Type())
// use Elem do dereference *Stunded
// and then use Set to set the Student to the content of theValue
newValue.Elem().Set(reflect.ValueOf(theValue))
fmt.Printf("Key: %v, Value: %v, value pointer %p\n", key, newValue.Elem().Interface(), newValue.Interface())
// return the newValue *Student
traversalTag(newValue.Interface())
}
}
https://go.dev/play/p/pNL2wjsOW5y
.Elem()或者,只需從 the 中洗掉traversalTag,然后您就不必將指標傳遞給它。
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)
for i := 0; i < elem.NumField(); i {
fmt.Printf("Tag name %s, value %s\n", elem.Field(i).Name, elem.Field(i).Tag)
}
}
https://go.dev/play/p/EwJ5e0uc2pd
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/445160.html
