golang - 为什么一个接口变量既可以被赋值为一个结构体实例,又可以被赋值为结构体指针

查看:577
本文介绍了golang - 为什么一个接口变量既可以被赋值为一个结构体实例,又可以被赋值为结构体指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

示例代码

type mInterface interface {
    foo()
}

type mStruct  struct {
    mInterface
}

func (m mStruct) foo() {
    // do something
}

func main() {
    var tmp mInterface = mStruct {}
    fmt.Printf("%v\n", tmp)
    tmp = new(mStruct)
    fmt.Printf("%v\n", tmp)
}

测试输出

{}
&{}

为什么tmp这个变量在这里既可以是指针,也可以是实例?

解决方案

查阅了一下资料,觉得是自己对golanginterface理解不够正确。

官方文档 中对Interface是这样定义的:

An interface type specifies a method set called its interface. A
variable of interface type can store a value of any type with a method
set that is any superset of the interface. Such a type is said to
implement the interface. The value of an uninitialized variable of
interface type is nil.

即是说interface类型的变量可以保存含有属于这个interface类型方法集的任何类型的值,而*mStruct包含mStruct*mStruct的所有方法,因此实现了接口,所以可以赋值给tmp

这篇关于golang - 为什么一个接口变量既可以被赋值为一个结构体实例,又可以被赋值为结构体指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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