使用结构体的步骤
- 定义结构体 ( type struct {…} )
- 实例化结构体 ( var 变量名 变量类型 )
- 使用结构体( 使用 结构体名.成员 对其进行操作 )
标准实例化
格式:
var 结构体实例 结构体
举例:
package main
import "fmt"
type Book struct {
title, author string
num, id int
}
func main() {
var book Book
fmt.Println(book)
}
// { 0 0}
因为 title 和 author 是string类型,因此空字符为 “ ”
num和id是 int 类型 ,因此默认的初始化的量为 0
使用关键字 new() 完成初始化
使用格式:
var 结构名 = new(结构体)
或者
结构名 := new(结构体)
举例:
package main
import "fmt"
type Book struct {
title, author string
num, id int
}
func main() {
var book Book
book1 := new(Book)
var book2 = new(Book)
fmt.Println("标准实例化结构体: ", book)
fmt.Println("new实例化结构体: ", book1)
fmt.Println("var + new 实例化结构体: ", book2)
}
// 标准实例化结构体: { 0 0}
// new实例化结构体: &{ 0 0}
// var + new 实例化结构体: &{ 0 0}
取地址实例化
使用格式 :
结构体实例 := &结构体类型{ }
举例:
package main
import "fmt"
type Book struct {
title, author string
num, id int
}
func main() {
book3 := &Book{}
fmt.Println("取地址实例化结构体: ", book3)
}
// 取地址实例化结构体: &{ 0 0}
结构体访问成员
结构体实例化完成后,可通过“.”来访问结构体的成员变量,对成员变量进行赋值或修改
举例:
package main
import "fmt"
type Book struct {
title, author string
num, id int
}
func main() {
book := new(Book)
book.author = "author"
book.title = "title"
book.num = 12
book.id = 12345
fmt.Println("结构体book中的内容: ", book)
fmt.Println("结构体book中的author: ", book.author)
fmt.Println("结构体book中的title: ", book.title)
fmt.Println("结构体book中的num: ", book.num)
fmt.Println("结构体book中的id: ", book.id)
}
// 结构体book中的内容: &{title author 12 12345}
// 结构体book中的author: author
// 结构体book中的title: title
// 结构体book中的num: 12
// 结构体book中的id: 12345