小编典典

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

go

我刚刚完成Go tour,我对指针和接口感到困惑。为什么这个 Go 代码不能编译?

package main

type Interface interface {}

type Struct struct {}

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

    _, _ = pi, ps
}

即如果Struct是一个Interface,为什么不是*Struct一个*Interface

我得到的错误信息是:

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

阅读 180

收藏
2021-11-10

共1个答案

小编典典

当您有一个实现接口的结构时,指向该结构的指针也会自动实现该接口。这就是为什么您从来没有*SomeInterface在函数原型中使用的原因,因为这不会向 中添加任何内容SomeInterface,并且您不需要在变量声明中使用这种类型。

接口值不是具体结构的值(因为它具有可变大小,这是不可能的),但它是一种指针(更准确地说是指向结构的指针和指向类型的指针)。Russ Cox在这里准确地描述了它:

接口值表示为两个字对,给出一个指向存储在接口中的类型信息的指针和一个指向相关数据的指针。

在此处输入图片说明

这就是为什么Interface,而不是*Interface保存指向实现 的结构的指针的正确类型Interface

所以你必须简单地使用

var pi Interface
2021-11-10