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

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

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的方法集包括所有声明了接收器类型为*TT的方法(也就是说,它还包含了T的方法集)。

在你的情况下,&t(类型为*Contractor)的方法集包括所有声明了接收器类型为*ContractorContractor的方法,因此它包含了doSomething()方法。

这也在Go FAQGo代码审查评论以及许多过去的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.

huangapple
  • 本文由 发表于 2021年5月28日 05:47:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/67730376.html
匿名

发表评论

匿名网友

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

确定