为什么我不能将* Struct分配给*接口? [英] Why can't I assign a *Struct to an *Interface?

查看:116
本文介绍了为什么我不能将* 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 中添加任何内容,并且你在变量声明中不需要这样的类型(参见)。

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


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




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

所以你必须简单地使用

  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 :

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.

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分配给*接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆