胖鸭 2012-11-22 10:55
浏览 116
已采纳

为什么我不能将 * Struct 分配给接口?

I'm just working through the Go tour, and I'm confused about pointers and interfaces. Why doesn't this Go code compile?

package main

type Interface interface {}

type Struct struct {}

func main() {
    var ps *Struct
    var pi *Interface
    pi = ps

    _, _ = pi, ps
}

i.e. if Struct is an Interface, why wouldn't a *Struct be a *Interface?

The error message I get is:

prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
        *Interface is pointer to interface, not interface

转载于:https://stackoverflow.com/questions/13511203/why-cant-i-assign-a-struct-to-an-interface

  • 写回答

2条回答 默认 最新

  • 关注

    When you have a struct implementing an interface, a pointer to that struct implements automatically that interface too. That's why you never have *SomeInterface in the prototype of functions, as this wouldn't add anything to SomeInterface, and you don't need such a type in variable declaration (see this related question).

    An interface value isn't the value of the concrete struct (as it has a variable size, this wouldn't be possible), but it's a kind of pointer (to be more precise a pointer to the struct and a pointer to the type). Russ Cox describes it exactly here :

    Interface values are represented as a two-word pair giving a pointer to information about the type stored in the interface and a pointer to the associated data.

    enter image description here

    This is why Interface, and not *Interface is the correct type to hold a pointer to a struct implementing Interface.

    So you must simply use

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

报告相同问题?

悬赏问题

  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 动态规划算法实现背包问题
  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少
  • ¥15 按颜色进行点云分割-python
  • ¥15 Matlab如何实现汽车变道切入场景的批量仿真