簡體   English   中英

結構嵌入提升方法問題中的結構

[英]Struct in struct embedding promoted methods question

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) 之所以有效,是因為方法調用隱式地獲取了接收者的地址。

規范說

如果(的類型)x 的方法集包含 m 並且參數列表可以分配給 m 的參數列表,則方法調用 xm() 是有效的。 如果 x 是可尋址的並且 &x 的方法集包含 m,則 xm() 是 (&x).m() 的簡寫:

表達式t2.type1Meth2()(&t2).type1Meth2()簡寫,因為t2是可尋址的,而type1Meth2()*type2的方法集中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM