? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 結構體
1、結構體的定義:
type ?name ?struct {? ?
? ? ? ? ? name1 ?type1? ?
? ? ? ? ? name2 ?type2? ?
? ? ? ? ? ?...
}
2、結構體簡單用法:
type person struct {
? ? name string
? ? age? int
}
func main() {
? ? var s person
? ? s.name = "lxc"
? ? s.age = 25
? ? fmt.Println(s) //{lxc 25}
?}
3、make和new的區別:
make只能用來構建切片(slice)、map和channel。
make:The make built-in function allocates and initializes an object of type slice, map, or chan (only).
make:內置函數make只能給slice、map或chan分配內存并初始化一個對象。
new:The new built-in function allocates memory.。
new:內置函數new用來分配內存。
注意:從源碼中的注釋可以看出,make分配并同時初始化了。new只是簡單分配了地址。
slice、map和chan只能用make,不能用new的原因:
ep:
var sl = new([]int);
fmt.Println(sl,len(*sl),cap(*sl))? //&[] 0 0
切片的長度和容量都為0,所以sl[0] = 100肯定是不對的。