type identifier struct {
field1 type1
field2 type2
...
}
複製代碼
結構體得字段能夠是任何類型,甚至是結構體自己,也能夠是函數或者接口git
type Point struct { x, y int }
複製代碼
new函數獲取到得是結構體類型得指針github
使用new函數跟使用&T{}是等價的,都是產生結構體類型指針編程
獲取結構體類型 編程語言
混合字面量語法ide
point1 := Point{0, 3} (A)
point2 := Point{x:5, y:1} (B)
point3 := Point{y:5} (C)
複製代碼
結構體的類型定義在它的包中必須是惟一的,結構體的徹底類型名是:packagename.structname函數
point.x = 5
複製代碼
x := point.x
複製代碼
type myStruct struct { i int }
var v myStruct // v是結構體類型變量
var p *myStruct // p是指向一個結構體類型變量的指針
複製代碼
結構體和它所包含的數據在內存中是以連續塊的形式存在的佈局
Go不支持面向對象編程語言中的構造方法,可是能夠經過函數實現spa
type File struct {
fd int // 文件描述符
name string // 文件名
}
// 定義工廠方法,函數名大寫字母開頭才能被跨包調用
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
return &File{fd, name}
}
// 調用工廠方法
f := NewFile(10, "./test.txt")
複製代碼
若是想要強制使用工廠函數,那麼能夠將結構體的類型改成首字母小寫3d
結構體中的字段,除了名字和類型,還有一個可選的標籤,它是附屬在字段的字符串(至關於字段的解釋)指針
type TagType struct { // tags
field1 bool "An important answer"
field2 string "The name of the thing"
field3 int "How much there are"
}
func main() {
tt := TagType{true, "Barak Obama", 1}
for i := 0; i < 3; i++ {
refTag(tt, i)
}
}
func refTag(tt TagType, ix int) {
// 使用reflect包
ttType := reflect.TypeOf(tt)
ixField := ttType.Field(ix)
fmt.Printf("%v\n", ixField.Tag)
}
複製代碼
// 字段名稱分別是:bool, string, int
type TagType struct {
bool
string
int
}
複製代碼
在結構體中,對於每種數據類型,只能有一個匿名字段
Go語言的繼承是經過內嵌或組合來實現的
結構體的屬性首字母大寫
type TagType struct {
Field1 bool
Field2 string
Field3 int
}
複製代碼
入門教程推薦: github.com/Unknwon/the…