这个问题是在看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()
}