package main
import "fmt"
//聲明一個(gè)新的類型
type person struct {
name string
avg int
}
//比較兩個(gè)人的年齡,返回年齡大的那個(gè)人,并且返回年齡差
//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
//兩個(gè)字段都寫(xiě)清楚的初始化
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)
}
我們上面介紹了如何定義一個(gè)struct,定義的時(shí)候是字段名與其類型一一對(duì)應(yīng),實(shí)際上Go支持只提供類型,而不寫(xiě)字段名的方式,也就是匿名字段,也稱為嵌入字段。
當(dāng)匿名字段是一個(gè)struct的時(shí)候,那么這個(gè)struct所擁有的全部字段都被隱式地引入了當(dāng)前定義的這個(gè)struct:
// struct2.go
package main
import (
"fmt"
)
type Human struct {
name string
age int
weight int
}
type Student struct {
Human //匿名字段,那么默認(rèn)struct就包含了Human所有字段
speciality string
}
func main() {
//初始化一個(gè)學(xué)生
mark := Student{Human{"Mark", 25, 100}, "Computer Science"}
//訪問(wèn)相應(yīng)的字段
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)
//修改對(duì)應(yīng)的信息
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)
}