type 標識符 struct {
Name string
Age int
Score int
}
二、struct 中字段訪問:和其餘語言同樣,使用點
例子
type Student struct {
Name string
Age int
Score int
}
func main(){
var stu Student
stu.Name = "lilei"
stu.Age = 22
stu.Score = 20
fmt.Printf("name=%s age=%d score=%d",stu.Name,stu.Age,stu.Score)
}
三、struct定義的三種形式:
a: var stu Student
b: var stu *Student = new(Student)
c: var stu *Student = &Student{}
(1)其中b和c返回的都是指向結構體的指針,訪問形式以下
stu.Name、stu.Age和stu.Score 或者(*stu).Name、(*stu).Age、(*stu).Scroe
3、struct的初始化
一、struct的內存佈局:struct中的全部字段在內存是連續的,佈局以下:
type Rect1 struct { Min, Max point}
type Rect2 struct { Min, Max *point}
二、鏈表定義string
type School struct {
Name School
Next *School
}
每一個節點包含下一個節點的地址,這樣把全部的節點串起來,一般把鏈表的第一個節點叫作鏈表頭
三、雙鏈表定義
type School struct {
Name string
Next *School
Prev *School
}
若是有兩個指針分別指向前一個節點和後一個節點叫作雙鏈表。
四、二叉樹定義
type School struct {
Name string
Left *School
Right *School
}
若是每一個節點有兩個指針分別用來指向左子樹和右子樹,咱們把這樣的結構叫作二叉樹
4、特殊自處
一、結構體是用戶單獨定義的類型,不能和其餘類型進行強制轉換
二、golang中的struct沒有構造函數,通常可使用工廠模式來解決這個問題
package model
type student struct {
Name string
Age int
}
func NewStudent(name string,age int) *student {
return &student{
Name:name,
Age:age,
}
}
package main
S := new(student)
S := model.NewStudent("tom",20)
三、咱們能夠爲struct中的每一個字段,寫上一個tag。這個tag能夠經過反射的機制獲取到,最經常使用的場景就是json序列化和反序列化。
type student struct {
Name string `json="name"`
Age string `json="age"`
}
四、結構體中字段能夠沒有名字,即匿名字段
type Car struct {
Name string
Age int
}
type Train struct {
Car
Start time.Time
int
}
五、匿名字段的衝突處理
type Car struct {
Name string
Age int
}
type Train struct {
Car
Start time.Time
Age int
}
type A struct {
a int
}
type B struct {
a int
b int
}