结构体内嵌
Go语言的结构体内嵌是一种组合特性,使用结构体内嵌可构建一种面向对象编程思想中的继承关系。 结构体实例化后,可直接访问内嵌结构体的所有成员变量和方法。
使用格式:
type 结构体名1 struct {
成员变量1 类型1
成员变量2 类型2
}
type 结构体名2 struct {
结构体名1
成员变量3 类型3
}
举例:
package main
import "fmt"
type Book struct {
title string
author string
num int
id int
}
type BookBorrow struct {
Book
borrowTime string
}
type BookNotBorrow struct {
Book
readTime string
}
func main() {
bookBorrow := &BookBorrow{}
bookNotBorrow := &BookNotBorrow{}
fmt.Println(bookBorrow)
fmt.Println(bookNotBorrow)
}
结构体内嵌的初始化
使用结构体的键值完成初始化操作:
package main
import "fmt"
type Book struct {
title string
author string
num int
id int
}
type BookBorrow struct {
Book
borrowTime string
}
type BookNotBorrow struct {
Book
readTime string
}
func main() {
bookBorrow := &BookBorrow{ // 键值初试化
Book: Book{title: "golang", author: "Tom",
num: 20, id: 123456,
},
borrowTime: "2022.01.02",
}
bookNotBorrow := &BookNotBorrow{ // 列表初始化
Book: Book{"python",
"Jan",
10,
654321,
},
readTime: "2022.01.03",
}
fmt.Println(bookBorrow)
fmt.Println(bookNotBorrow)
}
当然可以使用 结构体实例化名.成员变量 = 值 的形式完成初始化。
package main
import "fmt"
type Book struct {
title string
author string
num int
id int
}
type BookBorrow struct {
Book
borrowTime string
}
type BookNotBorrow struct {
Book
readTime string
}
func main() {
bookBorrow := &BookBorrow{ // 键值初试化
Book: Book{title: "golang", author: "Tom",
num: 20, id: 123456,
},
borrowTime: "2022.01.02",
}
// bookNotBorrow := &BookNotBorrow{ // 列表初始化
// Book: Book{"python",
// "Jan",
// 10,
// 654321,
// },
// readTime: "2022.01.03",
// }
bookNotBorrow := &BookNotBorrow{} // 使用结构体属性完成初始化操作
bookNotBorrow.Book.title = "c++"
bookNotBorrow.Book.author = "peter"
bookNotBorrow.Book.num = 50
bookNotBorrow.Book.id = 789456
bookNotBorrow.readTime = "2022.01.04"
fmt.Println(bookBorrow)
fmt.Println(bookNotBorrow)
}