非零基础自学Golang
第9章 结构体
9.4 初始化结构体
上一小节我们讲解了在结构体实例化后,再使用“.”的方式对成员变量进行赋值。另外,我们还可以在声明的同时对结构体的成员变量进行赋值。
Go语言中可以通过键值对格式和列表格式对结构体进行初始化。
9.4.1 键值对格式初始化
键值对初始化的格式如下:
结构体实例 := 结构体类型{成员变量1:值1,成员变量2:值2,成员变量3:值3,
}
这种类型的初始化类似于对map数据类型的初始化操作,键和值之间以冒号分隔,键值对之间以逗号分隔。
[ 动手写 9.4.1]
package mainimport "fmt"type Book struct {title stringauthor stringnum intid int
}func main() {book1 := &Book{title: "Go语言",author: "Tom",num: 20,id: 152368,}fmt.Println("title: ", book1.title)fmt.Println("author: ", book1.author)fmt.Println("num: ", book1.num)fmt.Println("id: ", book1.id)}
运行结果
9.4.2 列表格式初始化
如果觉得使用键值对初始化结构体的方式比较麻烦,那么我们可以使用一种类似列表的方式对结构体进行初始化,格式如下:
结构体实例 := 结构体类型{值1,值2,值3,
}
注意:
- 使用这种方式初始化结构体必须初始化所有的成员变量。
- 值的填充顺序必须和结构体成员变量声明顺序保持一致。
- 该方式与键值对的初始化方式不能混用。
[ 动手写 9.4.2]
package mainimport "fmt"type Book struct {title stringauthor stringnum intid int
}func main() {book1 := &Book{"Go语言","Tom",20,152368,}fmt.Println("title: ", book1.title)fmt.Println("author: ", book1.author)fmt.Println("num: ", book1.num)fmt.Println("id: ", book1.id)
}
运行结果