package main
import "fmt"
//1.构造函数
type person struct{
name string
city string
age int
address string
}
func newperson(name,city,address string,age int ) *person{
return &person{
name:name,
city:city,
age:age,
address:address,
}
}
//2.Method Receiver
/*func (接收者变量 接收者类型) 方法名(参数列表) (返回参数) {
函数体
}*/
func (p person)Method(){
fmt.Printf("%v,%v\n",p.name,p.age)
}
//3.指针型Method Receiver
func (p *person)Method1(newage int){
p.age=newage
}
//4.匿名字段
type Person1 struct{
string
//string
//int
//int
int
//string
}//不能重复
func message() Person1{
p:=Person1{
"李四",
//"CHinese",
//18,
//180,
75,
//"江苏省徐州市",
}
return p
}
//5.嵌套结构体
type user struct{
name string
age int
address Address
}
type Address struct{
province string
city string
}
func message1(){
p1:=user{}
p1.name="王五"
p1.age=18
p1.address=Address{
province:"江苏省",
city:"徐州市邳州市",
}
fmt.Printf("%#v\n",p1)
p2:=user{
name:"李四",
age:19,
address:Address{
province:"江苏省",
city:"徐州市邳州市",
},
}
fmt.Printf("%#v\n",p2)
}
//6.继承性
type animal struct{
name string
age int
}
func (a *animal)move(){
fmt.Printf("%s会动",a.name)
}
func (a *animal)message2(){
fmt.Printf("姓名:%s;年龄:%d",a.name,a.age)
}
type dog struct{
like string
animal *animal
}
type cat struct{
like string
animal *animal
}
func (a *dog)like1(){
fmt.Printf("%s喜欢%s\n",a.animal.name,a.like)
}
func (a *cat)like2(){
fmt.Printf("%s喜欢%s\n",a.animal.name,a.like)
}
func main() {
//1
p1:=newperson("张三","徐州","江苏省徐州市",18)
fmt.Printf("%#v\n",p1) //&main.person{name:"张三", city:"徐州", age:18, address:"江苏省徐州市"}
fmt.Printf("%T\n",p1)//*main.person
//2,3
p1.Method()//张三,18
p1.Method1(30)
fmt.Println(p1.age)//30
p2:=message()
//4
fmt.Printf("%#v\n",p2)
fmt.Printf("%T\n",p2) /*main.Person1{string:"李四", int:75} main.Person1*/
//5
message1() /*main.user{name:"王五", age:18, address:main.Address{province:"江苏省", city:"徐州市邳州市"}}
main.user{name:"李四", age:19, address:main.Address{province:"江苏省", city:"徐州市邳州市"}}*/
//6
p3:=&dog{
like:"骨头",
animal:&animal{
name:"快快",
age:3,},
}
p4:=&cat{
like:"鱼",
animal:&animal{
name:"乐乐",
age:3,
},
}
fmt.Printf("%#v\n",p3)
fmt.Printf("%T\n",p3)
p3.like1()
fmt.Printf("%#v\n",p4)
fmt.Printf("%T\n",p4)
p4.like2()
/*&main.dog{like:"骨头", animal:(*main.animal)(0xc000004540)}
*main.dog
快快喜欢骨头
&main.cat{like:"鱼", animal:(*main.animal)(0xc000004580)}
*main.cat
乐乐喜欢鱼*/
}
Go结构体进阶
最新推荐文章于 2024-08-21 14:16:47 发布