go 匿名字段
来源:互联网 发布:时尚网络电玩怎么样 编辑:程序博客网 时间:2024/06/05 04:55
原文: http://studygolang.com/articles/781
定义一个struct,定义的时候是字段名与其类型一一对应,实际上Go语言支持只提供类型,而不写字段名的方式,也就是匿名字段,或称为嵌入字段。
当匿名字段是一个struct的时候,那么这个struct所拥有的全部字段都被隐式地引入了当前定义的这个struct。
type Human struct {
name string
age int
weight int
phone string
}
不仅仅是struct字段,所有的内置类型和自定义类型都可以作为匿名字段
type Skills []string
type Student struct {
Human // 匿名字段,那么默认Student就包含了Human的所有字段
Skills //匿名字段
speciality string
phone string
}
type Skills []string
mark.Skills = []string{"anatomy"}
fmt.Println("His name is ", mark.name)
最外层的优先访问,也就是当你通过student.phone访问的时候,是访问student里面的字段,而不是human里面的字段。
fmt.Println("Student phone is ", mark.phone)
fmt.Println("Student phone is ", mark.Human.phone)
Go语言中的结构体可以定义匿名字段。Go语言中没有对象,但是结构体却有大量对象的功能。并且用匿名字段的确可以实现对象的继承和重载
A1得到了A的所有字段,A称为匿名字段。A1同样也得到A的所有方法,这个可称为继承:
type A struct{}
func (self *A)do() {
}
type A1 struct {
}
func main(){
}
在A1中能定义和A中重名的方法,这个可称为重写: 重写方法和字段一样,遵循最外层的优先访问原则
type A struct{
}
func (self *A)do() {
}
type A1 struct {
}
func (self *A1) do() {
}
func main(){
}
- go 匿名字段
- Golang Go语言结构体中匿名字段暴露方法的优先级
- Go学习笔记 (二) : 流程控制(if,for,switch) 与 函数 与 struct (匿名字段)
- Go匿名函数
- go语言的匿名函数
- Go学习笔记:匿名成员
- go语言匿名函数的用法
- go chan使用 匿名函数执行
- Go匿名函数和闭包
- Go面向对象编程之匿名组合
- struct匿名字段和interface,断言
- go语言变参,匿名函数的多种用法
- Go语言中struct的匿名属性特征
- GO语言学习-匿名函数和闭包
- Go语言以匿名组合的方式实现继承
- Go 实现lamda、匿名函数和内联函数
- go语言闭包,匿名函数,变量使用
- Go语言编程(十三)之匿名组合
- Nginx实现websocket代理的方式
- poj2533 Longest Ordered Subsequence
- Android性能优化(二):APP启动优化
- java comparator及comparable的使用
- 图像处理中的卷积总结
- go 匿名字段
- 基础MPI: Hello MPI
- MyEclipse进入debug模式,f6按键不起作用
- poi根据模板导出excel
- Git LFS 2.0.0发布
- corbaloc:iiop:localhost:2809使用的由来
- android 事件拦截 (Viewpager不可以左右滑动)
- maven 命令行创建项目
- invalid PID number "" in "/usr/local/var/run/nginx/nginx.pid"