为什么我不能将 *Struct 分配给 *Interface? [英] Why can't I assign a *Struct to an *Interface?
问题描述
我刚刚完成Go tour,我对指针和接口感到困惑.为什么这段 Go 代码不能编译?
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
}
即如果Struct
是Interface
,为什么*Struct
不是*Interface
?
i.e. if Struct
is an Interface
, why wouldn't a *Struct
be a *Interface
?
我得到的错误信息是:
prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
*Interface is pointer to interface, not interface
推荐答案
当你有一个结构体实现一个接口时,指向该结构体的指针也会自动实现该接口.这就是为什么在函数原型中永远不会有 *SomeInterface
的原因,因为这不会向 SomeInterface
添加任何内容,并且在变量声明中不需要这样的类型(见 这个相关问题).
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).
接口值不是具体结构的值(因为它具有可变大小,这是不可能的),但它是一种指针(更准确地说是指向结构的指针和指针到类型).Russ Cox 在此处 对它进行了准确描述:
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.
这就是为什么 Interface
而不是 *Interface
是保存指向实现 Interface
的结构的指针的正确类型.
This is why Interface
, and not *Interface
is the correct type to hold a pointer to a struct implementing Interface
.
所以你必须简单地使用
var pi Interface
这篇关于为什么我不能将 *Struct 分配给 *Interface?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!