Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reflection 反射结构的类型错误_Reflection_Go - Fatal编程技术网

Reflection 反射结构的类型错误

Reflection 反射结构的类型错误,reflection,go,Reflection,Go,我有两个不同的包(pkg1、pkg2),首先我有从另一个包调用函数的代码 文件#1 文件#2 为什么类型是reflect.rtype而不是*User? 如何正确地将type传递给另一个pkg?reflect.TypeOf()返回一个reflect.type现在您正在做两件完全不同的事情:在第一次调用Println(正确的)时,这个reflect.type被包装在接口{}中(在调用Println期间)在第二个(错误的)中,在调用RegisterSturct时将reflect.Type包装在接口{}

我有两个不同的包(pkg1、pkg2),首先我有从另一个包调用函数的代码

文件#1

文件#2

为什么类型是
reflect.rtype
而不是
*User
? 如何正确地将type传递给另一个pkg?

reflect.TypeOf()返回一个
reflect.type
现在您正在做两件完全不同的事情:在第一次调用Println(正确的)时,这个
reflect.type
被包装在
接口{}
中(在调用Println期间)在第二个(错误的)中,在调用RegisterSturct时将
reflect.Type
包装在
接口{}
中,然后在调用Println时将其再次包装在另一个
接口{}
中。Println只删除了一层接口{}包装


对不起,这是胡说八道。我得多想一想。如果可能,将删除。此处给出的代码无法生成您所说的输出。请阅读有关创建(最小、完整且可验证的示例)的内容。您的代码段无效。当编辑以使其编译时(大部分缺少括号),这两个
Println
语句都使用Go1.4.2为我提供“*pkg1.User”。(注意,
fmt.Printf(“%T%#v\n”,u,u)
确实给出了
*reflect.rtype&reflect.rtype{…
;但这不是您声称使用的)。并且,如果您不想/期望使用
reflect.Type
,请期待并处理
reflect.Type
,或者不要传递它(即只需执行
pkg2.Register((*User)(nil))
).reflect.Type已经是接口类型。在调用
RegisterStruct
fmt.Println
期间,没有发生“在
接口{}
内包装”的情况,当然也没有双重包装。抱歉,这太快了。第二个只是接口值的副本,没有重新包装。将删除。
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
}
package pkg2

import "reflect"

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