GO 七、struct
struct
type Student struct {
Name string
Age int
}
func main(){
s1 := Student{}
s1.Name="Lin"
s1.Age=20
fmt.Println(s1)
s2 :=Student{
Name:"Lee",
Age:22,
}
fmt.Println(s2)
//指向結構的指針. 傳入的參數更改到s3自身.
s3 :=&Student{
Name:"Wang",
Age:22,
}
MakeAnStu(s3)
}
func MakeAnStu(s *Student){
s.Age=99
}
匿名結構
func main(){
a := &struct {
Name string
Age int
}{
Name: "joe",
Age:19,
}
}
type person struct {
Name string
Age int
Contact struct {
Phone,City string
}
}
func main(){
a := peroson{Name:"joe",Age:19,a.Contact.Phone="0923"
a.Contact.City="TW"
}
}
匿名結構
type person struct {
string
int
}
func main() {
a := person{"joe",19}
fmt.Println(a)
}
Compare
type person struct {
Name string
Age int
}
func main() {
a := person{Name:"joe",Age:19}
b := person{Name:"joe",Age:20}
fmt.Println(a==b) //false
}
類似繼承的,組合
=
type human struct{
Id int
}
type teacher struct{
hunam
Name string
Age int
}
type Student struct{
human
Habbit
}
func main(){
a := teacher{Name:"joe",Age:22,human:human{Id:0}} //初始化
a.Name="kkk"
a.Age=13
a.human.Id=20 //a.Id=10
}