Go - Struct
2017-05-21 15:03
92 查看
定义
go 语言中的struct与c的很相似,此外,go没有Class,也没有继承。stuct的格式为:type <name> struct{}
package main import ( "fmt" ) type person struct { Name string Age int } func main() { p := person{ Name: "Tony", Age: 23, } fmt.Println(p) } //output {Tony 23}
Struct是值类型
package main import ( "fmt" ) type person struct { Name string Age int } func ChangeAge(per person) { per.Age = 15 fmt.Printf("Call 'Change Age' function, new age is %d \n", per.Age) } func main() { p := person{ Name: "Tony", Age: 23, } fmt.Println(p) ChangeAge(p) fmt.Println(p) } //output {Tony 23} Call 'Change Age' function, new age is 15 {Tony 23}
我们可以看到,age属性只在func内部被修改,因此可以确定struct是值类型(传递给函数的参数为值的一个copy)
如何传递引用?
我们可以将函数的参数类型定义称为“一个指针”,即可package main import ( "fmt" ) type person struct { Name string Age int } func ChangeAge(per *person) { per.Age = 15 fmt.Printf("Call 'Change Age' function, new age is %d \n", per.Age) } func main() { p := person{ Name: "Tony", Age: 23, } fmt.Println(p) ChangeAge(&p) fmt.Println(p) } //output {Tony 23} Call 'Change Age' function, new age is 15 {Tony 15}
struct中的匿名字段
go 语言中,支持在struct中省略字段的名称,只保留其类型(匿名字段)package main import ( "fmt" ) type person struct { string int } func main() { p := person{ "Bob", 27, } fmt.Println(p) } // output {Bob 27}
匿名结构
go语言中,也支持定义匿名结构。package main import ( "fmt" ) func main() { p := struct { Name string Age int Sex string }{ Name: "Joe", Age: 26, Sex: "female", } fmt.Println(p) } //output {Joe 26 female}
使用嵌入字段来“模拟”继承关系
package main import ( "fmt" ) type person struct { Sex string } type teacher struct { person Name string Age int } func main() { t := teacher{ person: person{Sex: "feamle"}, Name: "Jill", Age: 28, } fmt.Println(t) t.Age = 30 t.Name = "Criss" t.person.Sex = "male" fmt.Println(t) } //output {{feamle} Jill 28} {{male} Criss 30}
相关文章推荐
- Go-struct嵌套初始化与赋值
- Go语言学习之struct(The way to go)
- php trait和go struct的匿名字段
- go语言[6] struct,JSON,文本和html模板
- Go 语言中struct, slice , map 比较
- How to serialize/unserialize type struct in GO
- Go基础系列:struct的导出和暴露问题
- Go语言学习笔记4——struct
- Go struct tag深入理解
- go struct 自定义标签获取
- GO语言struct语法
- Go语言中struct的匿名属性特征实例分析
- Go语言学习笔记 --- struct
- Go语言struct类型介绍
- go struct 类型
- 【Go入门教程6】struct类型(struct的匿名字段)
- 推荐一款工具可以把 json 转成 go 的 struct
- go struct作为值函数参数需要注意的地方
- GO_06:GO语言基础之struct
- Go conversion between struct and byte