Go语言结构体
Posted 鸿渐之翼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言结构体相关的知识,希望对你有一定的参考价值。
Go 语言中数组可以存储同一类型的数据,但在结构体中我们可以为不同项定义不同的数据类型。Go语言结构体与C语言相似伪代码如下参考:
定义结构体
type struct_variable_type struct {
member definition
member definition
...
member definition
}
实例:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
fmt.Println(Books{"hello", "hello", "Hello", 123456})
fmt.Println(Books{title: "Go language", author: "hello world", subject: "Go ", book_id: 12345678})
fmt.Println(Books{title: "Go language", author: "hello world"})
}
访问结构体成员
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* 声明 Book1 为 Books 类型 */
var Book2 Books /* 声明 Book2 为 Books 类型 */
Book1.title = "Go language"
Book1.author = "hello world"
Book1.subject = "Go langugage"
Book1.book_id = 100000
Book2.title = "C"
Book2.author = "hello world"
Book2.subject = "C language"
Book2.book_id = 200000
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)
fmt.Printf( "Book 2 title : %s\\n", Book2.title)
fmt.Printf( "Book 2 author : %s\\n", Book2.author)
fmt.Printf( "Book 2 subject : %s\\n", Book2.subject)
fmt.Printf( "Book 2 book_id : %d\\n", Book2.book_id)
}
结构体指针
Go语言结构体指针定义伪码:
var struct_pointer *Books
struct_pointer = &Book1
struct_pointer.title
实例:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* 声明 Book1 为 Books 类型 */
var Book2 Books /* 声明 Book2 为 Books 类型 */
Book1.title = "Go"
Book1.author = "hello world"
Book1.subject = "Go language"
Book1.book_id = 123456
Book2.title = "C"
Book2.author = "hello world"
Book2.subject = "C language"
Book2.book_id = 1234567
printBook(&Book1)
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)
}
以上是关于Go语言结构体的主要内容,如果未能解决你的问题,请参考以下文章