Go语言的struct和C语言的很相似
简单的struct定义
package main
import "fmt"
type test struct{
Name string
Age int
}
func main(){
a:=test{"yc",22}
fmt.Println(a)
}
或者
package main
import "fmt"
type test struct{
Name string
Age int
}
func main(){
a:=test{
Name:"john",
Age: 19,
}
fmt.Println(a)
}
关于struct的操作
package main
import "fmt"
type test struct{
Name string
Age int
}
func main(){
a:=test{}
fmt.Println(a)
a.Name="yc"
a.Age =22
fmt.Println(a)
}
关于结构体做参数
不用指针就是值传递,加上指针就可以改变源地址,注意用了指针但是依旧用.进行调用
package main
import "fmt"
type test struct{
Name string
Age int
}
func A(t* test){
t.Age = 15
}
func main(){
a:=&test{
Name:"john",
Age: 19,
}//get the address directely,a is ptr
A(a)
fmt.Println(a)
a.Age=20
fmt.Println(a)
}
可以直接取a为结构体地址,而且这样的a还兼容普通的类型操作,所以是常用情况
匿名结构
package main
import "fmt"
func main(){
a:=struct{
Name string
Age int
}{
Name:"joe",
Age:19,
}
fmt.Println(a)
}
嵌套结构体
package main
import "fmt"
type person struct{
Name string
Age int
Contact struct{
Phone,City string
}
}
func main(){
a:=person{
Name:"joe",
Age:19,
}
a.Contact.Phone="123456"
a.Contact.City="nih"
fmt.Println(a)
}
匿名字段
package main
import "fmt"
type person struct{
string
int
}
func main(){
a:=person{
"joe",
19,
}
fmt.Println(a)
}
注意匿名字段赋值的时候一定要按照声明次序
结构体的组合(Go语言没有继承)
嵌入
package main
import "fmt"
type human struct{
Sex int
}
type teacher struct{
human
Name string
Age int
}
type student struct{
human
Name string
Age int
}
func main(){
a:=student{Name:"joe",Age:19,human:human{Sex:0}};
b:=teacher{Name:"joe",Age:20,human:human{Sex:0}};
fmt.Println(a,b)
a.Sex=1
fmt.Println(a,b)
}