这里是 Golang 教程系列的第二十七部分。
Go 语言不支持继承,但支持组合。组合的一般定义是 放在一起
。举个例子比如:汽车。汽车是由轮子、发动机和其他各种零件组成的。
通过嵌入到结构体进行组合
组合可以通过在一个结构体中嵌入另一个结构体来实现。
一篇博客文章就是一个完美的写作范例。每个博客文章都有标题、内容和作者信息。这可以用构图完美地表现出来。在本教程的后续步骤中,我们将学习如何实现这一点。
我们首先先创建一个结构体 author
package main
import (
"fmt"
)
type author struct {
firstName string
lastName string
bio string
}
func (a author) fullName() string {
return fmt.Sprintf("%s %s", a.firstName, a.lastName)
}
在上面的代码片段中,我们使用字段 firstName、lastName 和 bio 创建了 author 结构。我们还添加了一个方法 fullName() author 是返回类型,它返回 author 的全名。
下一步是创建 pos
t结构。
type post struct {
title string
content string
author
}
func (p post) details() {
fmt.Println("Title: ", p.title)
fmt.Println("Content: ", p.content)
fmt.Println("Author: ", p.author.fullName())
fmt.Println("Bio: ", p.author.bio)
}
post
结构体有 title 字段、content。它还有一个嵌入的匿名字段 author。这个字段表示 post
结构是由 `author组成的。现在, post 结构体可以访问 author struct 的所有字段和方法。我们还在 post 结构中添加了details() 方法,用于打印 author、title、content、fullName 和 bio。
无论何时一个结构体字段嵌入到另一个结构体字段中,Go 都允许我们访问嵌入的字段,就好像它们是结构体外部的一部分一样。这意味着可以用 p.fullName() 替换上述代码第十一行中的 p.author.fullName()。因此,details() 方法可以重写如下
func (p post) details() {
fmt.Println("Title: ", p.title)
fmt.Println("Content: ", p.content)
fmt.Println("Author: ", p.fullName())
fmt.Println("Bio: ", p.bio)
}
现在我们已经准备好了 author 和 post 结构体,让我们通过创建博客来完成这个程序。
package main
import (
"fmt"
)
type author struct {
firstName string
lastName string
bio string
}
func (a author) fullName() string {
return fmt.Sprintf("%s %s", a.firstName, a.lastName)
}
type post struct {
title string
content string
author
}
func (p post) details() {
fmt.Println("Title: ", p.title)
fmt.Println("Content: ", p.content)
fmt.Println("Author: ", p.fullName())
fmt.Println("Bio: ", p.bio)
}
func main() {
author1 := author{
"Naveen",
"Ramanathan",
"Golang Enthusiast",
}
post1 := post{
"Inheritance in Go",
"Go supports composition instead of inheritance",
author1,
}
post1.details()
}
上面程序中的 main 函数在第三十一行中创建了一个新的 author。通过嵌入 author1 在第三十六行创建一个新帖子。这个程序打印
Title: Inheritance in Go
Content: Go supports composition instead of inheritance
Author: Naveen Ramanathan
Bio: Golang Enthusiast