1、结构体定义
需要用到type和struct语句。
type struct_variable_type struct {
member definition
member definition
member definition
}
变量声明:
variable_name := struct_variable_type {value1, value2, value3...}
varibale_name := struct_variable_type {key1:value1, key2:value2,...}
结构体变量创建:
type Book struct {
title string
author string
id int
}
//创建
fmt.Println(Book{"golong", "abc", 10})
//key=>value格式
fmt.Println(Book{title:"golong", author:"abc", id:10})
//忽略的值为0或者空
fmt.Println(Book{title: "golong", id:10})
2、访问结构体成员
结构体变量名.成员名
var book1 Book
book1.author = "shinered"
3、结构体指针
var book1 Book
book1.title = "go"
printBook(&book1)
func printBook(book *Book) {
fmt.Printf("Book title: %s\n", book.title)
fmt.Printf("Book title: %s\n", book.author)
}
3、利用指针改变结构体对应的值。
4、结构体中属性的首字母大小写问题
首字母大写相当于public,小写相当于private,相当于包package 来说的。
当要将结构体对象转换为JSON时,对象中属性必须为大写,才能正常转换为JSON。