dtkvlj5386 2015-06-11 20:43
浏览 5

反射结构的类型错误

I have 2 different packages(pkg1, pkg2), in first i have code that calls function from another package

file#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

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 ? And how do i correctly pass type to another pkg?

  • 写回答

1条回答 默认 最新

  • duankezong4064 2015-06-11 20:57
    关注

    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. Println just removes one layer of interface{}-wrapping.

    Sorry, this is nonsense. I'll have to think a bit more. Would delete if possible.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?