package main
import "fmt"
type person struct {
name string
age int
sex string
}
//结构体嵌套结构体
type Student struct {
//通过匿名字段实现继承操作
person //结构体名称作为结构体成员
id int
score int
}
func main01() {
var stu Student = Student{person{"张三丰",190,"男"},101,100}
//stu.id=101
结构体名称.父类成员信息
//stu.name="张三"
stu.person.name="张三"
//stu.score=100
//stu.sex="男"
//stu.age=18
fmt.Println(stu)
}
type person1 struct {
name string
age int
sex string
}
type student1 struct {
*person1 //指针匿名字段
id int
score int
}
func main02() {
var stu student1 = student1{&person1{"小龙女",38,"女"},105,66}
//var per=person1{"杨过",35,"男"}
//stu.person.name
//将结构体变量 赋值给结构体指针类型
//stu.person1=&per
//stu.person1=new(person1)
//stu.name = "郭襄"
//stu.person1.name = "郭小姐"
//stu.id = 101
//stu.score = 78
fmt.Println(stu)
fmt.Println(stu.name)
fmt.Println(stu.id)
fmt.Println(stu.score)
}type person1 struct {
name string
age int
sex string
}
type student1 struct {
*person1 //指针匿名字段
id int
score int
}
func main03() {
var stu student1 = student1{&person1{"小龙女",38,"女"},105,66}
//var per=person1{"杨过",35,"男"}
//stu.person.name
//将结构体变量 赋值给结构体指针类型
//stu.person1=&per
//stu.person1=new(person1)
//stu.name = "郭襄"
//stu.person1.name = "郭小姐"
//stu.id = 101
//stu.score = 78
fmt.Println(stu)
fmt.Println(stu.name)
fmt.Println(stu.id)
fmt.Println(stu.score)
}
type TestA struct {
name string
id int
}
type TestB struct {
TestA
sex string
age int
}
//注意结构体不能嵌套本结构体
//结构体可以嵌套本结构体指针类型 链表
type TestC struct {
//*TestC ok
//TestC//err
TestB
score int
}
func main04() {
var s TestC=TestC{TestB{TestA{"姆巴佩",10},"男",19},4}
//s.score=100
//s.TestC.score=100
//s.TestB.TestA.name="姆巴佩"
//s.name="李四"
//s.id=201
//s.sex="男"
//s.age=20
//s.score=10
fmt.Println(s)
}
//
//func add(a,b int) int{
// return a+b
//}
//1、定义函数类型
//2、为已存在的数据类型起别名
type Int int //1、预处理 2、编译 3、汇编 4、链接
//方法
//func (方法接收者)方法名(参数列表)返回值类型
func (a Int)add(b Int)Int{
return a+b
}
func main05() {
//result:=add(10,20)
//根据数据类型 绑定方法
var a Int=10
value:=a.add(20)
//var b Int
fmt.Println(value)
}
type Stu struct {
name string
age int
sex string
}
//方法 值传递
func (s Stu) PrintInfo() {
fmt.Println(s.name)
fmt.Println(s.age)
fmt.Println(s.sex)
}
// 地址传递
func (s *Stu) EditInfo(name string, age int, sex string) {
//(*s).name=name
//结构体指针可以直接调用结构体成员
s.name = name
s.age = age
s.sex = sex
//s.PrintInfo()
}
func main06(){
var s1 *Stu
s1=new(Stu)
s1.EditInfo("薛宝钗",24,"女")
s1.PrintInfo()
}
func main07() {
//var s Stu = Stu{"刘姥姥", 54, "女"}
对象.方法
//s.PrintInfo()
var s1 Stu = Stu{"王宝钗", 24, "女"}
s1.PrintInfo()
//(&s1).EditInfo("林黛玉",16,"女")//ok
//结构体变量可以直接使用结构体指针对应的方法
s1.EditInfo("林黛玉",16,"女")
s1.PrintInfo()
}
//方法是全局的 允许程序在所有文件访问 对象.方法
//父类不能继承子类信息
//子结构体继承父类结构体 允许使用父类结构体成员 允许使用父类的方法
//方法重写 在一个对象中不能出现相同的方法名 方法的接收者 带* 和不带* 表示一个相同的对象
//默认使用子类的方法 采用就进原则