我是 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 吗?
答案 0 :(得分:6)
来自Go spec:
<块引用>一个类型可能有一个方法集与之关联。方法集
接口类型是它的接口。任何其他类型的方法集T
由所有声明为接收器类型 T
的方法组成。方法集
对应指针类型*T
的就是所有方法的集合
用接收者 *T
或 T
声明(也就是说,它还包含方法
T
组)。
在您的情况下,&t
的方法集(类型为 *Contractor
)是使用接收器 *Contractor
或 Contractor
声明的所有方法的集合,因此它包含方法 doSomething()
。
这也在 Go FAQ 和 Go code review comments 中讨论。最后,许多过去的 Stack Overflow 问题(例如 this one 或 that one)都涵盖了这一点。