10 结构体struct

Go 中的struct与C中的struct非常相似,并且Go没有class
使用 type struct{} 定义结构,名称遵循可见性规则

type person struct{
Name string
Age int
}

func main(){
a := person{}
a.Name = "joe"
a.Age = 19
fmt.Println(a)

b := pserson{
Name : "jole",
Age : 12,
}
fmt.Println(b)
}

支持指向自身的指针类型成员
支持匿名结构,可用作成员或定义成员变量
匿名结构也可以用于map的值
可以使用字面值对结构进行初始化
允许直接通过指针来读写结构成员
相同类型的成员可进行直接拷贝赋值
支持 == 与 !=比较运算符,但不支持 > 或 <
支持匿名字段,本质上是定义了以某个类型名为名称的字段
嵌入结构作为匿名字段看起来像继承,但不是继承
可以使用匿名字段指针

func main(){
a := pserson{
Name : "jole",
Age : 12,
}
fmt.Println(a)

A(a) //这里传入不是地址 里面输出的age变13
fmt.Println(a) //这里输出的age还是12

A(&a) //这里传入是地址 里面输出的age变13
fmt.Println(a) //这里输出的age也是13

//为了更加方便那就可以
b := &pserson{
Name : "jole",
Age : 12,
}

fmt.Println(b)

A(b) //这里就可以直接传入地址
fmt.Println(b)

//匿名结构
c := &struct {
Name string
Age int
}{
Name : "joe"
Age : 19
}

}
func A(per *person){
per.Age =13
fmt.Println("A",per)
}

func B(per *preson){
}
---end

//嵌套匿名结构
type person struct {
Name string
Age int
Contact struct {
Phone string
City string
CN,Sex string//多个定义类型
}
}

func main(){
a := person{Name: "joe", Age: 19}
a.Contact.Phone = "12456" //只能通过这样的方式进行结构体中的结构体
a.Contact.City= "wenzhou"
fmt.Println(a)
}
--end

type person struct{//这样属于匿名结构
string
int
}

func main(){
a := person{ "joe", 18}
fmt.Println(a)
}
---end

//嵌入结构 类似预面向对象的继承
type human struct {
Sex int
}

type teacher struct {
human
Name string
Age int
}

type student struct {
human
Name string
Age int
}

func main() {
a := teacher{Name: "jjj", Age: 19, human: human{Sex: 0}}
b := teacher{Name: "jjj", Age: 20, human: human{Sex: 1}}
a.Age = "j23"
a.human.Sex = 100
a.Sex = 200 //嵌入式的特色
}

你可能感兴趣的:(10 结构体struct)