定义结构体的格式如下:
type struct_variable_type struct {
member definition;
member definition;
...
member definition;
}
type Book struct {
id int
name string
author string
}
初始化结构体的格式如下,使用key-value的形式初始化时忽略的字段为零值。
structure_variable_type {value1, value2...valuen}
structure_variable_type { key1: value1, key2: value2..., keyn: valuen}
func main() {
fmt.Println(Book{1,"clean code","xiongya"})//{1 clean code xiongya}
fmt.Println(Book{id:100,author:"xiongya",name:"clean code"})//{100 clean code xiongya}
fmt.Println(Book{author:"xiongya",name:"clean code"})//{0 clean code xiongya}
}
不管结构体还是结构体指针,都使用.来访问结构体成员。
func main() {
book:=Book{1,"clean code","xiongya"}
bookPointer:=&book
fmt.Println(book.name)
fmt.Println(bookPointer.author)
}
有疑问加站长微信联系(非本文作者)