Golang类型嵌入实现

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

Golang type embedding implement

问题

我有一个类型T,它嵌入了类型B,并且*B实现了接口I。*T可以赋值给类型I的变量,但对于类型T来说不行,这是否意味着(*T)的方法集包含了B的值接收器和指针接收器?

package main

import (
	"fmt"
)

type I interface {
	Foo()
}
type B struct {}
type T struct {
	B
}

func (a *B) Foo() {
	fmt.Println("Bar")
}

func main() {
	t := T{B{}}
    // var i I = t -> error
	var i I = &t
	i.Foo()
}
英文:

I have a type T which embed type B, and *B implements I. *T can be assigned to a variable of type I but not in the case of T, does this mean (*T)'s method set contains both value and pointer receiver of B?

package main

import (
	"fmt"
)

type I interface {
	Foo()
}
type B struct {}
type T struct {
	B
}

func (a *B) Foo() {
	fmt.Println("Bar")
}

func main() {
	t := T{B{}}
    // var i I = t -> error
	var i I = &t
	i.Foo()
}

答案1

得分: 8

是的,*T 的方法集中包含了接收者为 B*B 的方法。

规范:结构体类型:

给定一个结构体类型 S 和一个定义类型 T,被提升的方法将按照以下规则包含在结构体的方法集中:

  • 如果 S 包含一个嵌入字段 T,则 S*S方法集都包含了接收者为 T 的被提升的方法。*S 的方法集还包含了接收者为 *T 的被提升的方法。
  • 如果 S 包含一个嵌入字段 *T,则 S*S 的方法集都包含了接收者为 T*T 的被提升的方法。
英文:

Yes, method set of *T contains methods with receiver B and *B.

Spec: Struct types:

> Given a struct type S and a defined type T, promoted methods are included in the method set of the struct as follows:
>
> - If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
> - If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.

huangapple
  • 本文由 发表于 2021年8月17日 23:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68820200.html
匿名

发表评论

匿名网友

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

确定