接口(Interface)是指向对象的指针吗?

huangapple go评论113阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年6月4日 08:23:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/67830065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定