這個問題是在看go的Context原始碼的時候發現的。簡單來講就是,結構體A嵌入介面I,再將結構體A嵌入結構體B,實體化結構體B并回傳實體的指標,可以直接轉換成介面I型別。于是自己做了一個小測驗,具體代碼如下。請問這是什么原理,如果有相關記憶體模型說明就更好了。
package main
import "fmt"
var ctx TestInt
// TestInt is an interface
type TestInt interface {
func1()
func2()
func3()
}
func (*emptyCtx) func1() {
fmt.Println("func1")
}
func (*emptyCtx) func2() {
fmt.Println("func2")
}
func (*emptyCtx) func3() {
fmt.Println("func3")
}
type emptyCtx int
var (
background = new(emptyCtx)
)
// Background is a function
func Background() TestInt {
return background
}
// Struct1 is a struct
type Struct1 struct {
TestInt
str1 string
}
// Struct2 is a struct
type Struct2 struct {
Struct1
str2 string
}
func newStruct1(parent TestInt) Struct1 {
return Struct1{
TestInt: parent,
str1: "test1",
}
}
// NewStruct2 is a function
func NewStruct2(parent TestInt) TestInt {
return &Struct2{
Struct1: newStruct1(parent),
str2: "test2",
}
}
func main() {
ctx := Background()
ctx = NewStruct2(ctx)
ctx.func1()
ctx.func2()
ctx.func3()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/195610.html
標籤:go語言
上一篇:想寫個定時洗掉檔案的,提示module 'schedule' has no attribute 'every'
下一篇:VOIP:IP語音技術下載
