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

示例代码

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这个变量在这里既可以是指针,也可以是实例?

阅读 5.9k
2 个回答

查阅了一下资料,觉得是自己对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

新手上路,请多包涵

go语言中任何值都可以付给interface{}类型。

var tmp = interface{}
tmp = 12
fmt.Println(tmp)//output 12
tmp = "name"
fmt.Println(tmp)//output name
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题