Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
This syntax creates a new struct.
You can name the fields when initializing a struct.
Omitted fields will be zero-valued.
An & prefix yields a pointer to the struct.
Access struct fields with a dot.
You can also use dots with struct pointers - the pointers are automatically dereferenced
Structs are mutable.
var varName typeName? ? ? ? ? ? //①
varName := new(typeName)? ? ? ? //②
varName := typeName{[初始化值]}? //③
varName := &typeName{[初始化值]} //④
注: ①③返回 typeName 類(lèi)型變量冈钦;②④返回 *typeName 類(lèi)型變量跷坝;③④[]可省略;若無(wú)初始化值咧纠,則默認(rèn)為零值
初始化值可以分為兩種:
a. 有序: typeName{value1, value2, ...} 必須一一對(duì)應(yīng)
b. 無(wú)序: typeName{field1:value1, field2:value2, ...} 可初始化部分值
? 例:
? type Person struct {
? ? name string
? ? age int
? }
? p := Person{"James", 23}? //有序
? p := Person{age:23}? ? ? //無(wú)序