1 回答

TA貢獻1876條經驗 獲得超6個贊
如您所知,使用&theValue解析為類型*interface{}。該類型*interface{}不同于*Student您傳遞給traversalTagfrom的類型tryMapWithType。
如果要傳遞*Student給traversalTagfrom tryMapWithReflect,則需要使用反射創建該指針值。簡單的原生 Go 地址運算符&是不夠的。
當您擁有reflect.Value可尋址的 a 時,您需要做的就是調用該.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 中刪除 thetraversalTag然后就不必將指針傳遞給它。
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
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報