一、定义结构体及其三种初始化
示例程序:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
//创建一个新的结构体
fmt.Println(Books{"Go 语言", "www.runoob.com", "Go语言教程", 6495407})
//也可以使用key => value 格式
fmt.Println(Books{title: "Go语言", author: "www.runoob.com", subject: "Go>语言教程", book_id: 6495408})
//忽略的字段为0或空
fmt.Println(Books{title: "Go语言", author: "www.runoob.com"})
}
运行结果:
二、访问结构体及将结构体作为函数参数
实例:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func printBook(book Books) {
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 id: %d\n", book.book_id)
}
func main() {
var Book1 Books
var Book2 Books
//Book1描述
Book1.title = "Go 语言"
Book1.author = "www.runoob.com"
Book1.subject = "Go 语言教程"
Book1.book_id = 6495407
//Book2描述
Book2.title = "Python教程"
Book2.author = "www.runoob.com"
Book2.subject = "Python 语言教程"
Book2.book_id = 6495700
//打印Book1信息
printBook(Book1)
//打印Book2信息
printBook(Book2)
}
运行结果:
三、结构体指针
实例:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func printBook(book *Books) {
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 id: %d\n", book.book_id)
fmt.Println()
}
func main() {
var Book1 Books
var Book2 Books
//Book1描述
Book1.title = "Go 语言"
Book1.author = "www.runoob.com"
Book1.subject = "Go 语言教程"
Book1.book_id = 6495407
//Book2描述
Book2.title = "Python教程"
Book2.author = "www.runoob.com"
Book2.subject = "Python 语言教程"
Book2.book_id = 6495700
//打印Book1信息
printBook(&Book1)
//打印Book2信息
printBook(&Book2)
}
运行结果: