dtpxi88884 2017-07-01 19:44
浏览 183
已采纳

为什么我不能使用指向* interface {}的特定类型的指针?

I have the following function:

func bytesToData(data interface{}, b []byte) error {
    buf := bytes.NewBuffer(b)
    dec := gob.NewDecoder(buf)
    return dec.Decode(data)
}

I use this for getting struct data in and out of boltdb. What I'd like to do, is change that signature to:

func bytesToData(data *interface{}, b []byte) error

And then I'd like to be able to call it like this (b in this case is a gob-encoded Account)

acc := &Account{}
err := bytesToData(acc, b)

But when I do that, I get an error like Cannot use *Account for type *interface{}.

For now, I've just changed it back to interface{}. But then, if I pass in an Account or some other type directly without making it a pointer, gob throws an error. It seems like this should be checkable at compile time. And given that an argument of type interface{} accepts anything, why doesn't an argument of type *interface{} accept a pointer to anything?

  • 写回答

2条回答 默认 最新

  • duanbanzhi4419 2017-07-01 20:57
    关注

    The genericity of interface types in Go is not passed on to derived types. This applies to pointers (as you noticed), and also to slices, channels, etc. For example, you can't assign a []string to a []interface{}.

    There are various ways to explain this. For a Haskell programmer:

    Go does not have covariant or contravariant types. All type constructors (such as the * that creates a pointer type) are invariant. So even though Account and *Account (and all other types) are subtypes of interface{}, nothing is a subtype of *interface{} or []interface{}. This is sometimes inconvenient, but it keeps Go's type system and assignability rules much simpler.

    For a C programmer:

    An interface{} can hold a value of any type, but it does not hold it directly. Rather than being a variable-sized magic container, it is just a struct consisting of a pointer to a type and a pointer to a value. When you assign a concrete type to an interface{}, both of these fields are filled in. *interface{} is a pointer to one of these structs. When you try to assign a *Account to a *interface{}, there is nowhere to put the type information, because the *interface{} is a single machine word that just holds a pointer. So the compiler won't let you do that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题