標籤:struct
struct
-使用type<Name>struct{}定義結構,名稱遵循可見度規則
-支援指向自身的指標類型成員
-支援匿名結構、可作用成員或定義成員變數
-匿名結構也可以用於MAP的值
-可以使用字面值對結構進行初始化
-允許值通過指標來讀寫結構成員
-相同類型的成員可進行直接拷貝賦值
-支援==與!=比較子,不支援>或<
-支援匿名欄位,本質上是定義了以某個類型名稱的欄位
-嵌入結構作為匿名欄位看起來像繼承、但不是繼承
-可以使用匿名欄位的指標
package main
import "fmt"
type test struct{}
func main(){
a :=test{}
fmt.Println(a)
}
package main
import "fmt"
type test struct {
Name string
Age int
Address string
}
func main() {
a := test{}
a.Name = "YH" //值初始化,與其他語言的class類似,GO語言沒有指標運算,
a.Age = 18
fmt.Printf("我叫%s, 今年年方%d\n", a.Name, a.Age)
b := test{
Name: "YH",
Age: 19,
Address: "Japan",
}
fmt.Printf("我叫%s, 今年年方%d,我是%s\n人", b.Name, b.Age, b.Address)
}
//匿名結構
package main
import "fmt"
type test struct {
Name string
Age int
Address string
Contact struct {
User_phont string
City string
}
}
func main() {
a := test{Name: "yh", Age: 19, Address: "Bj"}
a.Contact.User_phont = "1234567890"
a.Contact.City = "haidian"
fmt.Println(a)
}
package main
import "fmt"
func main() {
a := struct {
Name string
Age int
}{
Name: "aa",
Age: 19,
}
fmt.Println(a)
}
package main
import "fmt"
type test struct{
Name string
Age int
}
func main(){
a :=test{
Name:"coolqi", //設定字面值初始化
}
a.Age=19//
fmt.Println(a)
}
package main
import "fmt"
type humen struct{
Sex int
}
type Teacher struct{
humen
Name string
Age int
}
type Student struct{
humen //這裡的嵌入式是一個匿名的欄位,本質上是將結構的名稱作為欄位名稱,若需要作為字面值初始化,需要做humen:humen{Sex:1}
Name string
Age int
}
func main(){
a :=Teacher{Name:"joe",Age:19,humen:humen{Sex:1}}//在嵌入式結構中,
fmt.Println(a)
}
本文出自 “DBAspace” 部落格,請務必保留此出處http://dbaspace.blog.51cto.com/6873717/1963454
GO語言struct文法