2 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
您使用嵌入的變體實(shí)際上并未嵌入。嵌入字段是匿名的,然后Go會(huì)自動(dòng)委托。
這將您的示例簡(jiǎn)化為:
type EvenCounter3 struct {
INumber
}
func (this *EvenCounter3) IncTwice() {
this.Inc() // using this.n.Inc() twice makes it slower
this.Inc()
}
請(qǐng)注意,String()是自動(dòng)委派的(在Go語(yǔ)言中為“提升”)。
至于兩次調(diào)用Inc()會(huì)使它變慢,那是使用接口的限制。接口的重點(diǎn)是不公開(kāi)實(shí)現(xiàn),因此您無(wú)法訪問(wèn)其內(nèi)部數(shù)字變量。

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
我不確定我是否正確理解您要達(dá)到的目標(biāo)。也許是這樣的?
package main
import "fmt"
type Num interface {
Inc()
String() string
}
type Int32 struct {
int32
}
func (n *Int32) Inc() {
(*n).int32++
}
func (n Int32) String() string {
return fmt.Sprintf("%d", n.int32)
}
type EventCounter interface {
Num
IncTwice()
}
type Event struct {
Num
}
func (e Event) IncTwice() {
e.Inc()
e.Inc()
}
func main() {
e := Event{&Int32{42}}
e.IncTwice()
fmt.Println(e)
}
(在這里)
輸出
44
- 2 回答
- 0 關(guān)注
- 191 瀏覽
添加回答
舉報(bào)