func (t1 type1) type1meth1():\n " />
登录
首页 >  Golang >  Go问答

结构中嵌套结构的提升技术问题

来源:stackoverflow

时间:2024-03-26 09:06:37 133浏览 收藏

嵌套结构提升问题:在 Go 中,结构体中嵌套结构体的提升机制存在一个问题。如果嵌套结构体的方法具有指针接收器,那么外层结构体的方法集中将包含对该指针接收器方法的提升。即使外层结构体不直接拥有该指针接收器方法,也会发生这种情况。

问题内容

package main

import "fmt"

type type1 struct { //t
}

func (t1 type1) type1meth1() {
    fmt.printf("==> func (t1 type1) type1meth1():\n type: %t\n value: %+v\n\n", t1, t1)
}

func (t1 *type1) type1meth2() {
    fmt.printf("==> func (t1 *type1) type1meth2():\n type: %t\n value: %p\n contains: %+v\n\n", t1, t1, t1)
}

func (t1 type1) type1meth3() {
    fmt.printf("==> func (t1 type1) type1meth3():\n type: %t\n value: %+v\n", t1, t1)
}

type type2 struct { //s
    type1
}

func (t2 *type2) type1meth3() {
    fmt.printf("==> func (t2 *type2) type1meth3(): type: %t\n value: %+v\n\n", t2, t2)
}
func main() {
    t2 := type2{}
    t2.type1meth1() // type2 contains method set of type1
    t2.type1meth2() // not sure, why this works? type2 does not have method set of *type1 (a)
    t2.type1meth3() // type2 contains method set of type1. intercepted by embedding type type2 and called with *type2 receiver
}

给我:

$ go run embed-struct-in-struct.go
==> func (t1 type1) type1Meth1():
 Type: main.type1
 Value: {}

==> func (t1 *type1) type1Meth2():
 Type: *main.type1
 Value: 0x116be80
 Contains: &{}

==> func (t2 *type2) type1Meth3(): Type: *main.type2
 Value: &{type1:{}}

go version
go version go1.17.2 darwin/amd64

不确定为什么调用 (a) 有效? 文档说:提升的方法包含在结构体的方法集中,如下所示:

给定一个结构体类型 s 和一个定义的类型 t,提升的方法将包含在该结构体的方法集中,如下所示:

如果s包含嵌入字段t,则s和*s的方法集都包括接收者t的提升方法。*s的方法集还包括接收者*t的提升方法。 如果 s 包含嵌入字段 *t,则 s 和 *s 的方法集都包含接收者为 t 或 *t 的提升方法。


正确答案


(A) 之所以有效,是因为该方法调用隐式获取接收者的地址。

根据问题中引用的升级规则,方法 (*type1).type1Meth2() 将升级为 *type2

section of the specification on calls 说:

T2.TYPE1METH2()(&T2).TYPE1METH2()的shorthand,因为T2ZQBT2ZQBEND CQBEND CQBEN -ZQBCBCBCBCZQ iSQBCZQBEB Z1; *type2

到这里,我们也就讲完了《结构中嵌套结构的提升技术问题》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>