英文:
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
.
> 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论