Go语言学习-- No.11结构体--结构体内嵌

结构体内嵌

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值