【go从零单排】结构嵌套struct embedding

🌈Don't worry , just coding!
内耗与overthinking只会削弱你的精力,虚度你的光阴,每天迈出一小步,回头时发现已经走了很远。

📗概念

在Go语言中,结构体嵌套(struct embedding)是一种强大的特性,它允许在一个结构体中嵌入另一个结构体,从而实现组合和复用。嵌套结构体可以让你创建更加复杂的数据结构,同时保持代码的简洁性和可读性。

💻代码

go 复制代码
package main

import "fmt"

// type关键字定义base struct
type base struct {
	num int
}

// 定义函数describe,输入一个base类型,输出一个string
func (b base) describe() string {
	return fmt.Sprintf("base with num=%v", b.num)
}

// container结构嵌套base
type container struct {
	base
	str string
}

func main() {
	//使用字段初始化嵌套结构,指明了base
	//co是container的实例
	co := container{
		base: base{
			num: 1,
		},
		str: "some name",
	}
	//使用co.num 、co.str访问字段
	fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
	//用全名访问字段co.base.num
	fmt.Println("also num:", co.base.num)
	//访问describe方法co.describe()
	fmt.Println("describe:", co.describe())
	//定义接口describer,内部调用describe方法
	type describer interface {
		describe() string
	}
	//实现接口,调用co结构,由于base已经被嵌套进来,可以直接实现base中的describe方法
	var d describer = co
	fmt.Println("describer:", d.describe())
}

//输出go run post.go
//co={num: 1, str: some name}
//also num: 1
//describe: base with num=1
//describer: base with num=1

🔍理解

  • 被嵌套的结构体字段直接可以访问,方法可以直接被调用
  • 代码复用:可以将公共字段和方法定义在一个结构体中,然后在其他结构体中嵌套,避免重复代码。
  • 逻辑分组:将相关的字段组合在一起,使得数据结构更加清晰。
  • 简化访问:嵌套结构体的字段可以直接通过外部结构体访问,无需每次都指定嵌套结构体的名称。

💡 Tips小知识点

💪无人扶我青云志,我自踏雪至山巅。

相关推荐
lifewange2 小时前
Go语言-开源编程语言
开发语言·后端·golang
白毛大侠2 小时前
深入理解 Go:用户态和内核态
开发语言·后端·golang
九皇叔叔3 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity
王码码20353 小时前
Go语言中的数据库操作:从sqlx到ORM
后端·golang·go·接口
lifallen4 小时前
从零推导 Agent Summarization Middleware
人工智能·语言模型·golang·agi
低代码布道师4 小时前
纯代码实战:MBA培训管理系统 (十四) ——用户管理(批量选择与批量删除)
javascript·nextjs
Hello--_--World5 小时前
JavaScript运行机制、v8原理、js事件循环
开发语言·javascript·ecmascript
lifallen5 小时前
Agent Team (多智能体协同)
人工智能·语言模型·golang·agi
敲敲了个代码8 小时前
React 那么多状态管理库,到底选哪个?如果非要焊死一个呢?这篇文章解决你的选择困难症
前端·javascript·学习·react.js·前端框架
打瞌睡的朱尤9 小时前
js复习--考核
开发语言·前端·javascript