网站常识,wordpress添加跳转页面模板,徐州建网站,此网站不支持下载视频怎么办#x1f308;Don’t worry , just coding! 内耗与overthinking只会削弱你的精力#xff0c;虚度你的光阴#xff0c;每天迈出一小步#xff0c;回头时发现已经走了很远。
#x1f4d7;概念 在Go语言中#xff0c;结构体嵌套#xff08;struct embedding#xff09;是一…
Don’t worry , just coding! 内耗与overthinking只会削弱你的精力虚度你的光阴每天迈出一小步回头时发现已经走了很远。
概念 在Go语言中结构体嵌套struct embedding是一种强大的特性它允许在一个结构体中嵌入另一个结构体从而实现组合和复用。嵌套结构体可以让你创建更加复杂的数据结构同时保持代码的简洁性和可读性。 代码
package mainimport 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 {basestr 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.numfmt.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 cofmt.Println(describer:, d.describe())
}//输出go run post.go
//co{num: 1, str: some name}
//also num: 1
//describe: base with num1
//describer: base with num1理解
被嵌套的结构体字段直接可以访问方法可以直接被调用代码复用可以将公共字段和方法定义在一个结构体中然后在其他结构体中嵌套避免重复代码。逻辑分组将相关的字段组合在一起使得数据结构更加清晰。简化访问嵌套结构体的字段可以直接通过外部结构体访问无需每次都指定嵌套结构体的名称。 Tips小知识点
无人扶我青云志我自踏雪至山巅。