我有 2 个不同的包(pkg1、pkg2),首先我有从另一个包调用函数的代码
文件#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
}
文件#2
package pkg2
import "reflect"
func RegisterStruct(u interface{}) { // also tried to have argument type as reflect.Type
fmt.Println(u) //=> *reflect.rtype
}
为什么类型是 reflect.rtype
而不是 *User
?
我如何正确地将类型传递给另一个 pkg?
最佳答案
reflect.TypeOf()
返回一个 reflect.Type
现在你正在做两件完全不同的事情:在第一次调用 Println(“正确”的) 此 reflect.Type
包装在 interface{}
中(在调用 Println 期间),而在第二个(“错误”的)中包装 reflect.Type
在调用 RegisterSturct 时在 interface{}
中,然后在调用 Println 时再次将其重新包装在另一个 interface{}
中。 Println 只是移除了一层界面{}包装。
对不起,这是胡说八道。我得再考虑一下。如果可能会删除。
关于reflection - 错误的反射结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30791082/