英文:
Pass pointer as an interface type to the function
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是一个刚接触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) //为什么这行代码不会产生错误
}
在Go语言中,某些类型及其指针可以符合接口的要求。所以在我的例子中,t
和&t
都是Puller
类型的吗?
英文:
I am a new to Go and the behavior below confuses me:
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
}
In Go some type and pointer to this time conform to the interface? So in my example t and &t are both Pullers?
答案1
得分: 6
根据Go规范:
- 类型可以有与之关联的方法集。接口类型的方法集就是它自己。其他类型
T
的方法集包括所有声明了接收器类型为T
的方法。相应指针类型*T
的方法集包括所有声明了接收器类型为*T
或T
的方法(也就是说,它还包含了T
的方法集)。
在你的情况下,&t
(类型为*Contractor
)的方法集包括所有声明了接收器类型为*Contractor
或Contractor
的方法,因此它包含了doSomething()
方法。
这也在Go FAQ、Go代码审查评论以及许多过去的Stack Overflow问题中讨论过,比如这个问题或那个问题。
英文:
From the Go spec:
> A type may have a method set associated with it. The method set of an
> interface type is its interface. The method set of any other type T
> consists of all methods declared with receiver type T
. The method set
> of the corresponding pointer type *T
is the set of all methods
> declared with receiver *T
or T
(that is, it also contains the method
> set of T
).
In your case the method set of &t
(which is of type *Contractor
) is the set of all methods declared with receiver *Contractor
or Contractor
, so it contains the method doSomething()
.
This is also discussed in the Go FAQ, and in Go code review comments. Finally, this is covered by many past Stack Overflow questions like this one or that one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论