PHPer的Go之路 -- 结构体
简介
结构体是将零个或多个任意类型的变量,组合在一起的聚合数据类型,也可以看做是数据的集合。
Go的结构体(struct),有点像js的对象,用’.’链接。结构体表示一项记录,有点类似数据库的一条记录。
定义结构体
结构体定义需要使用 type 和 struct 语句。struct 语句定义一个新的数据类型,结构体中有一个或多个成员。type 语句设定了结构体的名称。结构体的格式如下:
package main
import ("fmt")
type Books struct {
book_id int
title string
author string
subject string
}
func main() {
//定义结构体
structTest()
}
func structTest() {
// 创建一个新的结构体,去掉key的话,需要一一对应
fmt.Println(Books{1,"Go", "臭大佬", "计算机语言"})
// 也可以使用 key => value 格式
fmt.Println(Books{title: "PHP", author: "Vijay", subject: "计算机语言", book_id: 2})
// 忽略的字段为 0 或 空
fmt.Println(Books{title: "Python", author: "魏花花"})
}
访问成员
如果要访问结构体成员,需要使用点号 . 操作符。
package main
import (
"fmt"
)
type Books struct {
book_id int
title string
author string
subject string
}
func main() {
structCall()
}
func structCall() {
var Book1 Books /*声明 Book1 为 Books 类型*/
Book1.title = "Go"
Book1.author = "臭大佬"
Book1.subject = "计算机语言"
Book1.book_id = 1
fmt.Printf("Book 1 title : %s\n", Book1.title)
fmt.Printf("Book 1 author : %s\n", Book1.author)
fmt.Printf("Book 1 subject : %s\n", Book1.subject)
fmt.Printf("Book 1 book_id : %d\n", Book1.book_id)
}
作为函数参数
你可以像其他数据类型一样将结构体类型作为参数传递给函数。并以以上实例的方式访问结构体变量:
package main
import (
"fmt"
)
type Books struct {
book_id int
title string
author string
subject string
}
func main() {
var Book1 Books /*声明 Book1 为 Books 类型*/
Book1.title = "Go"
Book1.author = "臭大佬"
Book1.subject = "计算机语言"
Book1.book_id = 1
/* 打印 Book1 信息 */
printBook(Book1)
}
func printBook( book Books ) {
fmt.Println("结构体作为参数")
fmt.Printf( "Book title : %s\n", book.title)
fmt.Printf( "Book author : %s\n", book.author)
fmt.Printf( "Book subject : %s\n", book.subject)
fmt.Printf( "Book book_id : %d\n", book.book_id)
}