简体   繁体   English

反射结构的类型错误

[英]Wrong type of reflected struct

I have 2 different packages(pkg1, pkg2), in first i have code that calls function from another package 我有2个不同的包(pkg1,pkg2),首先我有从另一个包调用函数的代码

file#1 文件#1

package pkg1
import "pkg2"
import "reflect"

type User struct {
  name string
  ...
}

func main() {
  fmt.Println(reflect.TypeOf((*User)(nil)) //=> *User
  pkg2.RegisterStruct(reflect.TypeOf((*User)(nil))
  //pkg2.RegisterStruct(reflect.TypeOf(&User{}) // also tried this way
}

file#2 文件#2

package pkg2

import "reflect"

func RegisterStruct(u interface{}) { // also tried to have argument type as reflect.Type
 fmt.Println(u) //=> *reflect.rtype
}

Why type was reflect.rtype instead of *User ? 为什么类型是reflect.rtype而不是*User And how do i correctly pass type to another pkg? 又如何正确将类型传递给另一个pkg?

The reflect.TypeOf() returns a reflect.Type now you are doing two completely different things with: In the first call to Println (the "correct" one) this reflect.Type is wrapped inside an interface{} (during the call to Println) while in the second (the "wrong" one) you wrap the reflect.Type inside an interface{} while calling RegisterSturct and you then rewrap it once more inside an additional interface{} while calling Println. reflect.TypeOf()返回一个reflect.Type现在您要做的是两个完全不同的事情:在第一次调用Println(“正确”)时,此reflect.Type被包装在一个interface{} (在调用期间) Println),而在第二个(“错误的”一个)中,您在调用RegisterSturct时将reflect.Type包装在一个interface{} ,然后在调用Println时再次将其reflect.Type包装在另一个interface{} Println just removes one layer of interface{}-wrapping. Println只是删除了一层界面{}包装。

Sorry, this is nonsense. 对不起,这是胡说。 I'll have to think a bit more. 我得再考虑一下。 Would delete if possible. 如果可能,将删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM