本文介绍了为什么我不能将* Struct分配给*接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是通过,我对指针和接口感到困惑。为什么这个Go代码不能编译?

  package main 

类型接口接口{}
$ b类型struct struct {}

func main(){
var ps * struct
var pi *接口
pi = ps

_,_ = pi,ps
}

即如果 Struct 是一个接口,为什么不会有一个 * Struct 是一个 *接口



我得到的错误信息是:

  prog.go:10:不能使用ps(类型* Struct)作为类型*赋值中的接口:
*接口是指向接口的指针,而不是接口


解决方案

当你有一个实现接口的结构时,该结构也会自动实现该接口。这就是为什么在函数原型中永远不会有 * SomeInterface ,因为这不会在 SomeInterface 中添加任何内容,并且你在变量声明中不需要这样的类型(参见:



这就是为什么界面,而不是 *界面是正确的键入一个指向实现接口的结构体的指针。

所以你必须简单地使用

  var pi界面


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
解决方案

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 :

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

这篇关于为什么我不能将* Struct分配给*接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:33