Go语言结构
使用指针引用结构还是挺奇怪的一件事,因为……没有->操作符了,只有. 于是就只能用点,有点搞不清到底是一个指针还是一个原始简单变量。
下面是一个打印书的程序,将书名等等信息打一下。在最后的函数printBook中,使用了指针指向一个结构Books。然后,在函数中直接写了book.title。如果是book Books,也是这么写:book.title。
本例子援引了另一个网站http://www.yiibai.com的例子,不过原来的例子错了,会有: syntax error: unexpected semicolon or newline before { 错误。因为把一个大括号换行放在第一个字符了。而go需要func的声明后面紧跟着大括号。
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
/* print Book1 info */
printBook(&Book1)
/* print Book2 info */
printBook(&Book2)
}
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 book_id : %d\n", book.book_id);
}