luo2pei4 2020-10-29 21:28
浏览 192

Go语言中结构体嵌入接口值的原理

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

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条