package main
import "fmt"
//1
type person struct{
name string
age int
weight float64
}
//2 匿名字段
type class struct{
person //匿名字段,默认继承
speciality string
}
// 3自定义匿名字段
type skill[]string
type school struct{
person //匿名,默认继承
skill //自定义匿名字段
int //自定义匿名字段
speciality string
}
func main() {
var P1 person //P person结构体
P1.name = "Astaixe"
P1.age = 20
var P2 person //P person结构体
P2.name = "li"
P2.age = 21
//1
P3, me:= P1.Older(P1,P2) //值传递,内存中一份拷贝
fmt.Printf("The Person popertity name=%s age=%d\n",P3.name,me)
//2
PPE,ME:=Oldl(P1,P2) //值传递一份拷贝
fmt.Printf("The Person popertity name=%s age=%d\n",PPE.name,ME)
//4
//
mark := class{person{"Mark", 25, 120}, "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)
//修改内置结构体
mark.person = person{"Marcus", 55, 220}
//fmt.Println("His name age is, ", mark.name,mark.age)
fmt.Println("His name is ", mark.name)
fmt.Println("His age is ", mark.age)
fmt.Println("His weight is ", mark.weight)
mark.person.age -= 1 //内置修改
fmt.Println("His age is", mark.age)
//5
// 初始化jane
//二级继承
jane :=school{person:person{"jane", 35, 120}, speciality:"Biology"}
// 现在我们来访问相应的字段
// 现在我们来访问相应的字段
fmt.Println("Her name is ", jane.name)
fmt.Println("Her age is ", jane.age)
fmt.Println("Her weight is ", jane.weight)
fmt.Println("Her speciality is ", jane.speciality)
// 我们来修改他的skill技能字段
jane.skill = []string{"anatomy"}
fmt.Println("Her skills are ", jane.skill)
fmt.Println("She acquired two new ones ")
jane.skill = append(jane.skill, "physics", "golang")
fmt.Println("Her skills now are ", jane.skill)
fmt.Println(jane)
// 修改匿名内置类型字段
jane.int = 3
fmt.Println("Her preferred number is", jane.int)
}
//struct 内部
func (P person)Older(p1,p2 person)(person,int){
if(p1.age>=p2.age){
return p1,p1.age-p2.age
}else{
return p2,p2.age-p1.age
}
}
//全局函数,golang不支持函数重载,运算符+可以多次参与运算,参考go lanauage
func Oldl(p1,p2 person)(person,int){
if(p1.age>=p2.age) {
return p1, p1.age - p2.age
}else{ //...//else 可以 省略
return p2,p2.age-p1.age
}
}
谢谢大家
有疑问加站长微信联系(非本文作者)