将指针作为接口类型传递给函数

时间:2021-05-27 21:47:27

标签: go pointers interface

我是 Go 的新手,下面的行为让我感到困惑:

package main

type Contractor struct{}

func (Contractor) doSomething() {}

type Puller interface {
    doSomething()
}

func process(p Puller) {
    //some code
}

func main() {
    t := Contractor{}
    process(&t) //why this line of code doesn't generate error
}

Go 中的一些类型和指针此时是否符合接口?所以在我的例子中,t&t 都是 Puller 吗?

1 个答案:

答案 0 :(得分:6)

来自Go spec

<块引用>

一个类型可能有一个方法集与之关联。方法集 接口类型是它的接口。任何其他类型的方法集T 由所有声明为接收器类型 T 的方法组成。方法集 对应指针类型*T的就是所有方法的集合 用接收者 *TT 声明(也就是说,它还包含方法 T 组)。

在您的情况下,&t 的方法集(类型为 *Contractor)是使用接收器 *ContractorContractor 声明的所有方法的集合,因此它包含方法 doSomething()


这也在 Go FAQGo code review comments 中讨论。最后,许多过去的 Stack Overflow 问题(例如 this onethat one)都涵盖了这一点。