我正在浏览Go游戏,我对指针和界面感到困惑.为什么这个Go代码没有编译?
package main
type Interface interface {}
type Struct struct {}
func main() {
var ps *Struct
var pi *Interface
pi = ps
_, _ = pi, ps
}
Run Code Online (Sandbox Code Playgroud)
即如果Struct是Interface,为什么不是*Struct一个*Interface?
我得到的错误信息是:
prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
*Interface is pointer to interface, not interface
Run Code Online (Sandbox Code Playgroud)
Den*_*ret 175
当你有一个实现接口的结构时,指向该结构的指针也会自动实现该接口.这就是为什么你从来没有*SomeInterface在函数的原型中,因为这不会添加任何东西SomeInterface,并且你不需要变量声明中的这种类型(参见这个相关的问题).
接口值不是具体结构的值(因为它具有可变大小,这是不可能的),但它是一种指针(更准确地说是指向结构的指针和指向该类型的指针) ).Russ Cox 在这里描述了它:
接口值表示为双字对,给出指向存储在接口中的类型的信息的指针和指向相关数据的指针.

这就是为什么Interface,而不是*Interface保持指向结构实现的指针的正确类型Interface.
所以你必须简单地使用
var pi Interface
Run Code Online (Sandbox Code Playgroud)
这也许就是你的意思:
package main
type Interface interface{}
type Struct struct{}
func main() {
var ps *Struct
var pi *Interface
pi = new(Interface)
*pi = ps
_, _ = pi, ps
}
Run Code Online (Sandbox Code Playgroud)
编译确定。另请参阅此处。