Go语言——结构体

一、定义结构体及其三种初始化

示例程序:

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)
}

运行结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值