go语言数组可以存储同一类型的数据 但在结构体中我们可以为不同项定义不同的数据类型
结构体是由一系列具有相同的类型或者不同类型的数据构成的数据集合
1.定义结构体
结构体定义需要使用type和struct语句。struct语句定义一个新的数据类型,结构体中有一个或者多个成员。
type语句设定了结构体的名称。结构体的格式如下
type struct_variable_type struct {
member definition;
member definition;
...
member definition;
}
一旦定义了结构体类型 就能用于变量的声明
variable_name := struct_variable_type {value1,value2...valuen}
访问结构体成员
如果要访问结构体成员 需要使用点号(.)操作符。 格式为:"结构体.成员名"
结构体类型变量使用struct关键字定义,实例如下
package main
import "fmt"
type Books struct {
title string
author string
subjectone string
book_id int
}
func main() {
var book1 Books //声明book1为Books类型
var book2 Books //声明book2为Books类型
book1.title = "Go语言"
book1.author = "超哥"
book1.subjectone = "教程"
book1.book_id = 123412
book2.title = "OC语言"
book2.author = "超哥哈哈哈"
book2.subjectone = "教程哈哈哈"
book2.book_id = 123412324
fmt.Printf("book1 title:%s,author:%s,subjectone:%s,book_id:%d\n",book1.title,book1.author,book1.subjectone,book1.book_id)
fmt.Printf("book2 title:%s,author:%s,subjectone:%s,book_id:%d\n",book2.title,book2.author,book2.subjectone,book2.book_id)
//调用
printBook(book1)
printBook(book2)
}
func printBook(book Books) {
fmt.Printf("title:%s,author:%s,subjectone:%s,book_id:%d\n",book.title,book.author,book.subjectone,book.book_id)
}
//结构体指针
//定义指向结构体的指针类似于其他指针变量
var struct_pointer *Books
//以上定义的指针变量可以存储结构体变量的地址。查看结构体变量地址,可以将&符号放到结构体变量前
struct_pointer = &book1;
//使用结构体指针访问结构体成员 使用"."操作符
struct_pointer.title;
//结构体指针重写
package main
import "fmt"
type Books struct {
title string
author string
subjectone string
book_id int
}
func main() {
var book1 Books
var book2 Books
book1.title = "Go语言"
book1.author = "超哥"
book1.subjectone = "教程"
book1.book_id = 4321
book2.title = "OC语言"
book2.author = "超哥哈哈哈"
book2.subjectone = "jia"
book2.book_id = 3214431
printBook(&book1)
printBook(&book2)
}
func printBook(book *Books) {
fmt.Printf("title:%s author:%s subjectone:%s book_id:%d\n",book.title,book.author,book.subjectone,book.book_id)
}