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 类型变量;②④返回 *typeName 类型变量;③④[]可省略;若无初始化值,则默认为零值
初始化值可以分为两种:
a. 有序: typeName{value1, value2, ...} 必须一一对应
b. 无序: typeName{field1:value1, field2:value2, ...} 可初始化部分值
例:
type Person struct {
name string
age int
}
p := Person{"James", 23} //有序
p := Person{age:23} //无序