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)
}
// 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)
}