英文:
Is an Interface a Pointer?
问题
假设我有以下类型定义:
type ICat interface {
Meow() string
}
type Cat struct {
Name string
}
func (c Cat) Meow() string {
return "Meow"
}
当我执行以下操作时:
var a Cat
a.Name = "Tom"
一个类型为Cat的结构体在内存中被分配,并且其中一个字段被赋值。
但是,如果执行以下操作:
var b ICat
在内存中到底分配了什么?Golang的接口只是一个持有指向另一个结构体的指针的结构体吗?一个"Boxed pointer"?
英文:
Suppose I have the following type definitions:
type ICat interface {
Meow() string
}
type Cat struct {
Name string
}
func (c Cat) Meow() string {
return "Meow"
}
When I perform this operation:
var a Cat
a.Name = "Tom"
A struct of type Cat is allocated in memory and one of its fields gets assigned.
But, if perform the following operation:
var b ICat
What is exactly being allocated in memory? is a Golang Interface just an struct that holds a pointer to another struct? a "Boxed pointer"?.
答案1
得分: 3
一个接口包含两个部分:指向底层数据的指针和该数据的类型。所以,当你声明
var b ICat
b
包含这两个元素。
当你执行:
b:=Cat{}
b
现在包含一个指向 Cat{}
的副本的指针,以及数据是 struct Cat
的事实。
当你执行:
b:=&Cat{}
b
现在包含指向 Cat{}
的指针的副本,以及它是 *Cat
的事实。
英文:
An interface holds two things: a pointer to the underlying data, and the type of that data. So, when you declare
var b ICat
b
contains those two elements.
When you do:
b:=Cat{}
b
now contains a pointer to a copy of Cat{}
, and the fact that the data is a struct Cat
.
When you do:
b:=&Cat{}
b
now contains a copy of the pointer to Cat{}
, and the fact that it is a *Cat
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论