Go语言struct类型介绍
struct
我们可以声明新的类型,作为其它类型的属性或字段容器。
如,创建一个自定义类型person代表一个人的实体。这个实体拥有属性:姓名&年龄。这样的类型我们称之为struct。
复制代码 代码如下:
type person struct{
name string
age int
}
复制代码 代码如下:
var P person // P 现在就是 person 类型的变量了
P.name = "Astaxie" // 赋值 "Astaxie" 给 P 的 name 属性 .
P.age = 25 // 赋值 "25" 给变量 P 的 age 属性
fmt.Printf("The person's name is %s", P.name) // 访问 P 的 name 属性 .
除了上面这种P的声明使用之外,还有其他两种声明使用方式
1、按照顺序提供初始化值
复制代码 代码如下:
P := person{"Liuxinming", 28}
2、通过field:value的方式初始化,这样可以任意顺序
复制代码 代码如下:
P := person{age:28, name:"Liuxinming"}
举例:
复制代码 代码如下:
package main
import "fmt"
//声明一个新的类型
type person struct {
name string
avg int
}
//比较两个人的年龄,返回年龄大的那个人,并且返回年龄差
//struct 也是传值的
func older(p1, p2 person) (person, int) {
if p1.avg > p2.avg { //比较p1和p2年龄
return p1, p1.avg - p2.avg
}
return p2, p2.avg - p1.avg
}
func main() {
var tom person
//赋值初始化
tom.name, tom.avg = "Tom", 18
//两个字段都写清楚的初始化
bob := person{avg: 25, name: "Bob"}
//按照struct定义顺序初始化
paul := person{"Paul", 43}
tb_Older, tb_diff := older(tom, bob)
tp_Older, tp_diff := older(tom, paul)
bp_Older, bp_diff := older(bob, paul)
fmt.Printf("Of %s and %s, %s is older by %d years\n",
tom.name, bob.name, tb_Older.name, tb_diff)
fmt.Printf("Of %s and %s, %s is older by %d years\n",
tom.name, paul.name, tp_Older.name, tp_diff)
fmt.Printf("Of %s and %s, %s is older by %d years\n",
bob.name, paul.name, bp_Older.name, bp_diff)
}
输出结果如下:
复制代码 代码如下:
Of Tom and Bob, Bob is older by 7 years
Of Tom and Paul, Paul is older by 25 years
Of Bob and Paul, Paul is older by 18 years
struct的匿名字段
我们上面介绍了如何定义一个struct,定义的时候是字段名与其类型一一对应,实际上Go支持只提供类型,而不写字段名的方式,也就是匿名字段,也称为嵌入字段。
当匿名字段是一个struct的时候,那么这个struct所拥有的全部字段都被隐式地引入了当前定义的这个struct:
复制代码 代码如下:
// struct2.go
package main
import (
"fmt"
)
type Human struct {
name string
age int
weight int
}
type Student struct {
Human //匿名字段,那么默认struct就包含了Human所有字段
speciality string
}
func main() {
//初始化一个学生
mark := Student{Human{"Mark", 25, 100}, "Computer Science"}
//访问相应的字段
fmt.Println("His name is ", mark.name)
fmt.Println("His age is ", mark.age)
fmt.Println("His weight is ", mark.weight)
fmt.Println("His speciality is ", mark.speciality)
//修改对应的信息
mark.speciality = "AI"
fmt.Println("Mark changed his speciality")
fmt.Println("His speciality is ", mark.speciality)
// 修改他的年龄信息
fmt.Println("Mark become old")
mark.age = 46
fmt.Println("His age is", mark.age)
// 修改他的体重信息
fmt.Println("Mark is not an athlet anymore")
mark.weight += 60
fmt.Println("His weight is", mark.weight)
}
输出结果:
复制代码 代码如下:
His name is Mark
His age is 25
His weight is 100
His speciality is Computer Science
Mark changed his speciality
His speciality is AI
Mark become old
His age is 46
Mark is not an athlet anymore
His weight is 160
下一篇:sublime安装支持go和html的插件