当前位置: 首页> 文旅> 旅游 > golang内嵌结构使用示例(结构中包含结构)

golang内嵌结构使用示例(结构中包含结构)

时间:2025/7/10 7:27:49来源:https://blog.csdn.net/fittec/article/details/139471100 浏览次数:0次

1.定义结构

// 定义基础结构
type base struct {num int //结构成员
}

2.实现结构成员num字段的get与set方法

func (b *base) Num() int {return b.num
}func (b *base) SetNum(num int) {b.num = num
}

3.在新结构中嵌入结构

// 在新结构中嵌入结构
type container struct {base        //嵌入的结构str  string //新结构字段
}

4.base结构实现方法descirbe

// describe:base结构实现方法descirbe
func (b base) describe() string {return fmt.Sprintf("base with num=%v", b.num)
}

5.使用结构base与container

//使用结构base与containercb := container{ //初始化结构containerbase: base{ //初始化结构basenum: 888, //base结构成员num},str: "Hello Container", //container结构成员str}fmt.Println("结构Container:", cb)fmt.Printf("结构Container对象cb={container->base->num: %v, container->str: %v}\n", cb.num, cb.str)fmt.Println("结构container内嵌结构base的num成员:", cb.base.num)fmt.Println("结构base的成员方法describe:container->base->describe()", cb.describe())

6.通过接口调用结构实现方法

//临时定义接口type describer interface {describe() string //跳到base结构的describe方法}fmt.Println("--->describe:", cb.describe()) //调用内嵌结构的describe方法cb.SetNum(999)var d describer = cb                        //调用base结构的SetNumfmt.Println("===>describer:", d.describe()) //调用接口describer,接口再转到base结构对接口的实现describe方法

关键字:golang内嵌结构使用示例(结构中包含结构)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: