原文:https://golangbot.com/inheritance/
欢迎访问Golang 系列教程中的第27章。
go 不支持继承(inheritance), 但是它支持组合(composition)。构图的一般定义是 “放在一起”。组合的一个示例是小轿车。汽车由轮子、引擎和其他各种各样的零件组成。
通过嵌入结构进行组合
通过将一个结构类型嵌入到另一个中, 可以在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
作为接收器类型, 并返回作者的全名。
下一步是创建post
结构。
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