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条)

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存